1. 安装apscheduler
2. apscheduler使用简介
- 2.1 demo
- 2.2 代码说明
- 3. 定时发送消息
本项目的源码链接:
hanfangyuan/wechat-robot,本文对应仓库tag为3.0
在上一篇
从零搭建微信机器人(二):发送文本消息中,我们已经知道了如何向微信发送文本消息,本篇博客将要介绍如何通过设置定时触发任务,自动向微信发送消息。
1. 安装apscheduler
apscheduler的全称是advanced python scheduler,使用pip命令直接安装pip install apscheduler
2. apscheduler使用简介
2.1 demo
from apscheduler.schedulers.blocking import BlockingScheduler
# 需要定时触发的任务函数,打印文本
def print_text(text1, text2):
print(text1, text2)
# 创建scheduler,timezone时区信息可以不设置,默认为系统时区
scheduler = BlockingScheduler(timezone="Asia/Shanghai")
# cron 触发器
# 每天七点半执行
scheduler.add_job(print_text, 'cron', ('cron:', 'good morning'), hour=7, minute=30)
# 整分钟时执行
scheduler.add_job(print_text, 'cron', ('cron:', 'hello world'), minute='*/1')
# interval 触发器
# 每隔一分钟执行一次,从程序开始运行时算起
scheduler.add_job(print_text, 'interval', ('interval:', 'hello world'), minutes=1)
# 开始scheduler start()后面如果还有代码不会被执行,程序在start被阻塞住
scheduler.start()
'''
运行结果
cron: hello world
interval: hello world
cron: hello world
interval: hello world
cron: hello world
interval: hello world
...
'''
2.2 代码说明
- scheduler.add_job(print_text, 'cron', ('cron:', 'good morning'), hour=7, minute=30) 该代码是添加要执行的任务,并且设置任务定时触发的方式,以及触发的时间。 参数说明:
- print_text是函数名称,注意名称后面没有括号。
- 'cron’是触发器类型,该类型表示在具体时刻执行任务, hour=7, minute=30即表示在每天7:30分执行传入的函数。除了hour, minute字段还有month,day,second字段,字段也可以设置许多类型的值,如下图。还可以把’cron’换成’interval’改成另一种触发器scheduler.add_job(print_text, 'interval', ('interval:', 'hello world'), minutes=1),该触发器表示间隔某一段时间周期性执行任务。
- (‘cron:’, ‘good morning’)是函数的参数,必须是元组的形式,即一个参数时也要写成(arg, )元组形式,传入的函数没有参数时省略该项。
- scheduler.start()程序在该处被阻塞,后面的代码不会被执行。
3. 定时发送消息
我们通过apscheduler把向微信发送消息的函数设置成定时触发的方式,当时间为整分钟时发送消息。代码如下:
import requests
import json
from apscheduler.schedulers.blocking import BlockingScheduler
# 企业id、key
CORP_ID = 'xxx' # 更换为你的企业id
CORP_SECRET = 'xxx' # 更换为你的应用secret
AGENT_ID = 1000002 #更换为你的应用id,注意是数字类型,不是字符串
# 获取token
def get_token():
token_api = (
'https://qyapi.weixin.qq.com/cgi-bin/gettoken?' +
f'corpid={CORP_ID}&corpsecret={CORP_SECRET}'
)
response = requests.get(token_api)
print(response.json())
return response.json()['access_token']
# 发送文本消息
def send_text_message(content, touser):
data = json.dumps({
"touser" : touser,
"msgtype" : "text",
"agentid" : AGENT_ID,
"text" : {
"content" : content
},
"safe":0
})
send_api = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?' + f'access_token={get_token()}'
res = requests.post(send_api, data=data).json()
print(res)
if __name__ == '__main__':
scheduler = BlockingScheduler(timezone="Asia/Shanghai")
# 整分钟时刻发送消息
scheduler.add_job(send_text_message, 'cron', ('hello world', '@all'), minute="*/1")
scheduler.start()
本篇文章主要介绍了python的apscheduler模块,使用该模块我们可以在某些时刻自动向微信推送消息,可以在微信上实现日程提醒等功能。为了使项目代码逻辑更清晰,下一篇将介绍对微信消息发送接口进行封装。