无需cron:用Python实现特定时间双周执行代码方案
双周定时任务实现方案(无需cron)
核心思路
基于你熟悉的schedule库保留定时触发逻辑,额外增加周数奇偶校验实现双周执行,同时通过时区处理确保任务严格按美国东部时间(EST)触发。
实现代码
import schedule import time from datetime import datetime import pytz # Python3.9+ 可替换为 zoneinfo 模块 # 配置目标时区(美国东部时间) est_timezone = pytz.timezone('US/Eastern') # Python3.9+ 替代写法:from zoneinfo import ZoneInfo; est_timezone = ZoneInfo("America/New_York") # 设置双周周期的基准起始周(选一个符合需求的周一作为起点,确保周期准确) base_week_start = est_timezone.localize(datetime(2024, 1, 1)) # 2024年1月1日为EST周一 def execute_task(): # 获取当前EST时间 current_est = datetime.now(est_timezone) # 计算当前周与基准周的周数差,取余判断是否为双周周期内 week_diff = (current_est.isocalendar()[1] - base_week_start.isocalendar()[1]) % 2 if week_diff == 0: print("test") # 按EST时间配置每周一1点触发任务检查 schedule.every().monday.at("01:00").do(execute_task) while True: schedule.run_pending() time.sleep(60) # 每分钟检查一次,降低资源消耗
关键细节说明
- 时区保真:必须用EST时区获取当前时间,避免本地时区偏差导致触发时间错误。
- 基准周调整:若需要改变双周的起始节点,修改
base_week_start为目标周一即可。 - 周数校验逻辑:通过
isocalendar()[1]获取当年周数,计算与基准周的差值取余,余数为0时执行任务,实现严格双周间隔。 - 资源优化:将原示例的
sleep(1)改为sleep(60),既满足定时精度,又减少不必要的CPU占用。
无schedule库替代方案
如果不想依赖schedule,可直接通过循环判断时间实现:
import time from datetime import datetime import pytz est_timezone = pytz.timezone('US/Eastern') base_week_start = est_timezone.localize(datetime(2024, 1, 1)) def task(): print("test") while True: current_est = datetime.now(est_timezone) # 校验:周一1点左右 + 双周周期匹配 if (current_est.weekday() == 0 and current_est.hour == 1 and (current_est.isocalendar()[1] - base_week_start.isocalendar()[1]) % 2 == 0): task() time.sleep(3600) # 执行后休眠1小时,避免重复触发 time.sleep(60) # 每分钟检查一次
内容的提问来源于stack exchange,提问作者bigbird342d
相关产品推荐
相关产品推荐

