Python 定时任务:每天晚上执行,次日早上结束
使用Python的time模块和datetime模块来实现定时执行任务。下面是一个示例代码:\n\npython\nimport time\nfrom datetime import datetime, timedelta\n\ndef run():\n\twhile True:\n\t\tcurrent_time = datetime.now()\n\t\tstart_time = current_time.replace(hour=22, minute=0, second=0, microsecond=0)\n\t\tend_time = current_time.replace(hour=8, minute=0, second=0, microsecond=0) + timedelta(days=1)\n\n\t\tif start_time <= current_time <= end_time:\n\t\t\tprint('hello world!')\n\t\ttime.sleep(60) # 每分钟检查一次时间\n\nrun()\n\n\n这段代码中,我们定义了一个run函数,其中通过datetime.now()获取当前时间,然后设置开始时间为每天晚上22点,结束时间为次日早上8点。在循环中,判断当前时间是否在开始和结束时间之间,如果是,则打印"hello world!"。为了避免频繁检查时间,我们使用time.sleep(60)每隔一分钟检查一次时间。这样就可以实现每天晚上开始执行,次日早上结束的效果。
原文地址: http://www.cveoy.top/t/topic/pYHX 著作权归作者所有。请勿转载和采集!