当中有无用代码, 根据需要自行删除!
"""
@File : time_task.py
@Time : 2022/09/10 11:13:16
@Author : JuYongkang
@Version : 1.0
@Contact : j_juyongkang@163.com
@Desc : 定期向企业微信推送消息
"""
import requests, json
import datetime
import time
import calendar
import schedule
from workalendar.asia import China
# 机器人url
wx_url = "xxxxxx" # 配置机器人url
# 发送的消息
send_message = "消息体"
def get_current_time():
"""获取当前时间,当前时分秒"""
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
day = datetime.datetime.now().strftime('%Y%m%d')
hour = datetime.datetime.now().strftime("%H")
mm = datetime.datetime.now().strftime("%M")
ss = datetime.datetime.now().strftime("%S")
return now_time, day, hour, mm, ss
def search_day(day):
"""判断当前日期是否是工作日"""
cal = China()
date = datetime.datetime.now()
if not cal.is_working_day(date):
return False
return True
def sleep_time(hour, m, sec):
"""返回总共秒数"""
return hour * 3600 + m * 60 + sec
def send_msg(content):
"""艾特全部,并发送指定信息"""
# 打包请求体
data = json.dumps({"msgtype": "text", "text": {"content": content, "mentioned_list": []}})
# 附带请求体请求接口,
r = requests.post(wx_url, data, auth=('Content-Type', 'application/json'))
print(r.json)
# print('发送消息')
# def every_time_send_msg(interval_h=168, interval_m=0, interval_s=0, special_h="13", special_m="50", mode="special"):
def every_time_send_msg():
"""
每天指定时间发送指定消息
:param interval_h: 睡眠时间(时)
:param interval_m: 睡眠时间(分)
:param interval_s: 睡眠时间(秒)
:param special_h: 执行时间(时) 未用
:param special_m: 执行时间(分) 未用
:param mode: 执行模式
:return: 无
"""
mode = 'special'
c_now, c_day, c_h, c_m, c_s = get_current_time()
print("当前时间:", c_now, c_h, c_m, c_s)
s_time = time.time()
# 模式-
if mode == "special":
# 判断当前日期
state = search_day(c_day)
# 如果当前日期是工作日, 则判断当前时间是否是指定执行时间,若是,则执行,若不是,则
if state == True:
# if c_h == special_h and c_m == special_m:
# 执行
print("正在发送...")
send_msg(send_message)
now_time, now_day, now_h, now_m, now_s = get_current_time()
print('当前时间{},消息已发送完毕'.format(now_time))
e_time = time.time()
print('程序执行用时:', e_time - s_time)
# 发送消息完毕,睡眠30分钟,发送消息2
else:
# 当前日期不是工作日,不发送消息,睡眠30分钟
# print('今天是', data)
now_time, now_day, now_h, now_m, now_s = get_current_time()
print('当前时间{}未发送消息(不是工作日)'.format(now_time))
# 模式二
else:
# 此处未写模式二,忽略
pass
return
if __name__ == '__main__':
# 程序执行入口
"""
注: 程序每天9点发送消息至企业微信,只在工作日发送消息,节假日和休息日除外
"""
schedule.every().day.at('09:00').do(every_time_send_msg)
# schedule.every(2).seconds.do(every_time_send_msg)
while True:
schedule.run_pending()
time.sleep(1)