如何在Python中获得类似Cron的调度程序?我正在寻找一个Python库,它将提供at和cron比如功能。我非常希望有一个纯Python解决方案,而不是依赖安装在盒子上的工具;这样,我就可以在没有cron的机器上运行。对于那些不熟悉cron:您可以根据如下表达式调度任务: 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday
0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays.cron时间表达式语法不太重要,但我希望具有这种灵活性。如果没有什么东西能帮到我的话,我们会很感激地收到任何关于积木的建议。编辑我对启动过程不感兴趣,只是用Pythonpython函数编写的“作业”。当然,我认为这将是一个不同的线程,但不是在一个不同的过程。为此,我正在寻找cron时间表达式的表现力,但使用的是Python。克隆有已经有好几年了,但我想尽可能的随身携带。我不能指望它的存在。
3 回答
小唯快跑啊
TA贡献1863条经验 获得超2个赞
from datetime import datetime, timedeltaimport time# Some utility classes / functions firstclass AllMatch(set): """Universal set - match everything""" def __contains__(self, item): return TrueallMatch = AllMatch()def conv_to_set(obj): # Allow single integer to be provided if isinstance(obj, (int,long)): return set([obj]) # Single item if not isinstance(obj, set): obj = set(obj) return obj# The actual Event classclass Event(object): def __init__(self, action, min=allMatch, hour=allMatch, day=allMatch, month=allMatch, dow=allMatch, args=(), kwargs={}): self.mins = conv_to_set(min) self.hours= conv_to_set(hour) self.days = conv_to_set(day) self.months = conv_to_set(month) self.dow = conv_to_set(dow) self.action = action self.args = args self.kwargs = kwargs def matchtime(self, t): """Return True if this event should trigger at the specified datetime""" return ((t.minute in self.mins) and (t.hour in self.hours) and (t.day in self.days) and (t.month in self.months) and (t.weekday() in self.dow)) def check(self, t): if self.matchtime(t): self.action(*self.args, **self.kwargs)
c = CronTab( Event(perform_backup, 0, 2, dow=6 ), Event(purge_temps, 0, range(9,18,2), dow=range(0,5)))
class CronTab(object): def __init__(self, *events): self.events = events def run(self): t=datetime(*datetime.now().timetuple()[:5]) while 1: for e in self.events: e.check(t) t += timedelta(minutes=1) while datetime.now() < t: time.sleep((t - datetime.now()).seconds)
添加回答
举报
0/150
提交
取消