简体   繁体   English

安排 Python 脚本在没有 cron 的情况下每周日运行

[英]Schedule Python Script to run every Sunday without cron

I have a python file by name Sample.py, which needs to be run once every Sunday irrespective of time.我有一个名为 Sample.py 的 python 文件,它需要每周日运行一次,无论时间如何。 I want the whole script to run, not just one function inside it.我希望整个脚本都能运行,而不仅仅是其中的一个函数。

Can this be done without using cron??这可以不使用cron来完成吗??

I tried searching for solutions, but couldn't find the right solution.我尝试寻找解决方案,但找不到正确的解决方案。 Please help me out with this.这个你能帮我吗。

Thank you in advance.先感谢您。

We can use the Python sched module and exec() the script.我们可以使用 Python sched模块和exec()脚本。 Thus given Sample.py :因此给出Sample.py

print ("Hello World")

... we can write another script sched_sample.py : ...我们可以编写另一个脚本sched_sample.py

import sched, time

dayLen = 86400  # seconds
weekLen = 7     # days

dayLen = 1      # We make the days 1 second long for testing

def onlyOnSunday ():
    tt = time.localtime()
    exec(open("./Sample.py").read())
    t = time.mktime(tt)+dayLen*weekLen
    s.enterabs (t,0,onlyOnSunday)

s = sched.scheduler(time.time, time.sleep)
tt = time.localtime()
t = time.mktime(tt)+(6-tt.tm_wday)*dayLen
s.enterabs (t,0,onlyOnSunday)
s.run ()    # Run all scheduled events

... which uses the method described in the most recent answer to Scheduling a task on python to initially schedule whatever was in Sample.py to run, exec ing it as described in an answer to What is an alternative to execfile in Python 3.0? ......它使用在最近的答案中描述的方法调度任务的蟒蛇最初计划无论是在Sample.py运行, exec荷兰国际集团它作为一个答案描述什么是在Python 3.0的execfile的替代? . . I'm using Python 3 but if you're using Python 2 you can just use execfile() directly.我使用的是 Python 3,但如果您使用的是 Python 2,则可以直接使用execfile()

Before the first call to s.enterabs() , we compute how many days are required to get to next Sunday and schedule the first run for then.在第一次调用s.enterabs() ,我们计算到达下个星期日需要多少天,然后安排第一次运行。 Subsequently, we just schedule for the next Sunday by adding a week's worth of seconds to the scheduled time.随后,我们只是通过将一周的秒数添加到预定时间来安排下一个星期天。 Note that the next time is calculated from the time obtained immediately after onlyOnSunday() is first called, so if Sample.py takes (say) an hour to run we won't have the scheduled time slipping later in the Sunday.请注意,下一次是根据第一次调用onlyOnSunday()后立即获得的时间计算的,因此如果Sample.py需要(例如)一个小时来运行,我们将不会在周日晚些时候安排计划时间。

Of course, the 100% Python solution adds a process to the system that wouldn't be needed if cron was used.当然,100% Python 解决方案向系统添加了一个如果使用cron就不需要的进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM