7
头图

Sometimes we need to execute a script regularly, then we can use cronjob to do it, for example:

 10 04 * * * /usr/local/bin/somework.sh

Sometimes, you only want this script to execute on weekdays, like this:

 10 04 * * 1-5 /usr/local/bin/somework.sh

But sometimes the working day is not a simple Monday to Friday, such as catching up with a small long holiday, sometimes you have to go to work on Saturday, and sometimes you don't go to work on Monday. At this time, such settings are easy to mess up, so how do we set them up? Can this cronjob allow him to predict our holiday schedule and make sure that it is not messed up at all?

Only cron is not enough, we need to call an open interface in the script to know the holiday arrangement, and then we can execute it as planned.

This open interface is here: https://github.com/NateScarlet/holiday-cn

We simply write a script:

 #!/usr/local/bin/python
"""每天定时执行脚本"""
import datetime
import requests


def will_work(date):
    """检查该天是否需要工作"""
    holiday_data = requests.get(
        url='https://natescarlet.coding.net/p/github/d/holiday-cn/git/raw/master/2022.json'
    ).json()
    # 放入公司规定的特殊考勤日
    holiday_data['days'].append({
        'date': '2022-06-21',
        'isOffDay': False
    })
    # 检查该日期是否在列表中
    days_in_list = [day for day in holiday_data['days'] if day['date']
                    == datetime.datetime.strftime(date, '%Y-%m-%d')]
    if days_in_list:
        # 是否在节假日倒休表里,如果在倒休表里,按倒休表作息
        return not (days_in_list[0]["isOffDay"])
    else:
        # 按照周一至周五作息
        return True if date.weekday() < 5 else False


def main():
    """主函数"""
    if will_work(datetime.datetime(2022, 6, 21, 0, 0, 0, 0)):
        print("今天要上班")
    else:
        print("今天不上班")


if __name__ == '__main__':
    main()

Give it execute permission:

 chmod +x somework.py

Then set a cronjob:

 10 04 * * * /usr/local/bin/somework.py

It can be done every working day.


张京
13.4k 声望4.7k 粉丝

现任北京联云天下科技有限公司技术副总裁。1994年毕业于清华大学计算机科学与技术专业;20多年软件开发及项目管理经验;历任亚洲生活网络公司CTO,摩托罗拉软件中心QSE工具经理,融信恒通技术总监,安必信软件公...


« 上一篇
Gitlab修复记