python 实现定时任务

需求:

想实现 每周一到周五下班钉钉打卡提醒,每周四发周报提醒

使用了二种方法实现

一:apscheduler,代码如下

 1 import json,requests,datetime
 2 from apscheduler.schedulers.blocking import BlockingScheduler
 3 access_token = 'XXXXXXXX' #钉钉token
 4 contentWee ='今天周四吆,记得发周报'
 5 contentPun = '下班不打卡,辛苦也白搭'
 6 
 7 def notify(access_token,conId,content,tele):
 8     '''
 9     钉钉通知
10     :param access_token: 
11     :param conId: 0:艾特所有人 1:艾特个人 2或其他:普通通知
12     :param content: 通知内容
13     :param tele: conId==1时使用,tele: [13800000000,13800000001]
14     :return: 
15     '''
16     url = 'https://oapi.dingtalk.com/robot/send?access_token=' + access_token
17 
18     if conId == 0:
19         # 艾特所有人
20         con = {
21             "msgtype": "text",
22             "text": {
23                 "content": content
24             },
25             "at": {
26                 "isAtAll": 'true',
27                 "atMobiles": [
28 
29                 ]
30             }
31         }
32     elif conId == 1:
33         # 艾特个人
34         con = {
35          "msgtype": "text",
36          "text": {
37              "content": content
38          },
39          "at": {
40              "isAtAll": 'false',
41              "atMobiles": tele
42              }
43      }
44     else:
45         # 普通通知
46         con = {
47             "msgtype": "markdown",
48             "markdown": {
49                 "title": "hhh",
50                 "text": content
51             },
52         }
53 
54 
55     data = json.dumps(con)
56     headers = {'content-type': 'application/json'}
57     r2 = requests.post(url, data=data, headers=headers)
58     print(r2.text)
59 
60 if __name__ == '__main__':
61     tele = [13800000000,13800000001]
62     scheduler = BlockingScheduler()
63     # mon-fri: 周一到周五,也可以写成 1-5 ,时间 18:30 ,ars:方法 notify入参;每周-到周五下午六点半执行notify方法
64     scheduler.add_job(notify, 'cron', day_of_week='mon-fri',  hour=18, minute=30, args=[access_token,1,contentPun,tele]) 
65     #同上,每周四下午4点执行notify方法
66     scheduler.add_job(notify, 'cron', day_of_week='thu', hour=16, minute=00, args=[access_token,4,contentWee,tele])
67     scheduler.start()


二、schedule 代码如下,阻塞流程

1 import json,requests,time,schedule,datetime
2 
3 #notify方法同一
4 if __name__ == '__main__':
5   schedule.every().thursday.at('16:00').do(notify,access_token,contentWee)  # 每周四 16.00执行
6   while True:
7       schedule.run_pending()

部署:
直接执行 nohup python 文件名 &

建议使用第一种调度方法



原文地址:https://www.cnblogs.com/whycai/p/11285000.html