Cron Job 运行 仅在一周中的特定日期的一系列日期

Cron Job to run on a range of days only on a particular day of week

0 0 2-31 * sun         /home/ubuntu/x.h
0 0 2-31 * mon-sat     /home/ubuntu/y.h

这最终 运行 他们两个。我是不是做错了什么?

这是 crontab 格式:

* * * * *
| | | | |
| | | | +---- Day of the Week   (range: 0-6, 0 standing for Sunday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

Ubuntu man 5 crontab 说:

  field          allowed values
  -----          --------------
  minute         0-59
  hour           0-23
  day of month   1-31
  month          1-12 (or names, see below)
  day of week    0-7 (0 or 7 is Sun, or use names)

所以,这应该适合你:

0 0 2-31 * 0         /home/ubuntu/x.h
0 0 2-31 * 1-6       /home/ubuntu/y.h

我不确定为什么 7 运行 在星期六——您的系统时间是否准确且时区正确?

编辑:啊,是的,很遗憾,您不能同时指定星期几和月份中的某一天。来自 man 5 crontab:

Note: The day of a command's execution can be specified by two fields — day of month, and day of week. If both fields are restricted (i.e., aren't *), the command will be run when either field matches the current time. For example, ``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday. One can, however, achieve the desired result by adding a test to the command (see the last example in EXAMPLE CRON FILE below).

所以,答案是:

0 0 2-31 * *       test $(date +\%u) -eq 7 && /home/ubuntu/x.h
0 0 2-31 * *       test $(date +\%u) -ne 7 && /home/ubuntu/y.h

$(date '+%u') returns 1-7 代表周一到周日。举个例子 echo $(date '+%u')

from datetime import datetime
from datetime import timedelta
import urllib.request

//urls to hit
urls=["https//:example1.com","https//:example2.com"
]

//function to hit url
def call(url):
 urllib.request.urlopen(url)

//function to get date 
def get_month_diff(current,nom):
    m1= current
    m2=m1 - timedelta(days=nom*30)
    m3=current
    m4=m2.replace(day=1)
    m5=m3.replace(day=1)-timedelta(days=1)
    list=str(m4).split(" ")[0].split("-")
    list.reverse()
    startDate="-".join(list)
    list1=str(m5).split(" ")[0].split("-")
    list1.reverse()
    endDate="-".join(list1)
    for i in range (0,5):
       call(urls[i]+""+startDate+"/"+endDate)
//main execution function
def solve():
    month=str(datetime.today()).split("-")[1]
    if month in ["01","04","07","10"] :get_month_diff(datetime.today(),3)
    if month in ["01","07"]:get_month_diff(datetime.today(),6)
    get_month_diff(datetime.today(),1)
solve()