如何使用python cron-tab安排每日,每月,每周的cron作业?

时间:2019-01-14 10:08:32

标签: python python-2.7 cron

我需要每天,每周,每月使用python运行一次cron作业。我做了很多研究,并决定使用crontab。这是我的配置:

"schedule" :  {
  "name": "xyz",
  "at": "12:00:00 AM",
  "every": "1d"
  } 

在这里,每个人每天,每周,每月都可以取1d,1w,1m的值。它还可以取值为2d,2w,2m等。我已经确定了每天和每月的代码。我坚持每周。有人可以帮忙吗?

my_cron = CronTab(user=self.user)
        for job in my_cron :
            if job.comment == self.name:
                my_cron .remove(job)
                my_cron .write()
        job = my_cron .new(
            command='sh start.sh "invoke-adapter"',
            comment=self.name)        
        job.setall(str_job_schedule)
        vmware_cron.write()

For monthly, str_job_schedule = "30 03 * */1 *" (runs every month)
For daily, str_job_schedule = "30 03 * * */1" (runs every day)
For weekly, str_job_schedule = "30 03 ? * *" 

2 个答案:

答案 0 :(得分:1)

我要指定哪一天

每月一次,每月的第1次

str_job_schedule = "30 03 1 * *"

每天每天午夜

str_job_schedule = "30 03 * * *"

每周的每个星期日

str_job_schedule = "30 03 * * 0"

此WP页说明了格式:https://en.wikipedia.org/wiki/Cron

答案 1 :(得分:0)

我做了非常相似的事情,并且基本上创建了一种调度程序。我将大致向您展示这个想法

import threading
from crontab import CronTab
import time
schedules = {'Jobs': {'clean house': '* * * * *'}, {'cook': '*/5 * * * *'}} # some kind of config of your jobs

while True:
    time.sleep(11)
    for job in schedules['Jobs']:
        entry = CronTab(schedules['Jobs'][job])
        if entry.next() < 9:
            # if the job is going to happen in less than 10s
            # run thread which will execute after time.sleep(entry.next())
            threading.Thread(target = execute,args=(job,)).start()