diff --git a/everyday_wechat/main.py b/everyday_wechat/main.py index fc5be98..b2beeb5 100644 --- a/everyday_wechat/main.py +++ b/everyday_wechat/main.py @@ -11,6 +11,7 @@ import random # from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler +from datetime import datetime as dt, timedelta import itchat from itchat.content import ( TEXT @@ -110,6 +111,18 @@ def init_data(): if alarm_dict: init_alarm(alarm_dict) # 初始化定时任务 +def set_daily_alarm(alarm_dict): + """ + 设置每天随机发送消息时间 + :param alarm_dict: 定时相关内容 + """ + sched = BackgroundScheduler() + for key, value in alarm_dict.items(): + start = dt.strptime(value['start'], '%H:%M').replace(year=dt.now().year, month=dt.now().month, day=dt.now().day) + end = dt.strptime(value['end'], '%H:%M').replace(year=dt.now().year, month=dt.now().month, day=dt.now().day) + run_time = start + timedelta(seconds=random.randint(0, int((end - start).total_seconds())),) + sched.add_job(send_alarm_msg, 'date', [key], run_date = run_time, id=key, misfire_grace_time=600) + sched.start() def init_alarm(alarm_dict): """ @@ -118,9 +131,8 @@ def init_alarm(alarm_dict): """ # 定时任务 scheduler = BackgroundScheduler() - for key, value in alarm_dict.items(): - scheduler.add_job(send_alarm_msg, 'cron', [key], hour=value['hour'], - minute=value['minute'], id=key, misfire_grace_time=600) + set_daily_alarm(alarm_dict) + scheduler.add_job(set_daily_alarm, 'cron', [alarm_dict], hour = 0, id='set_daily_alarm') scheduler.start() print('已开启定时发送提醒功能...') # print(scheduler.get_jobs()) diff --git a/everyday_wechat/utils/itchat_helper.py b/everyday_wechat/utils/itchat_helper.py index b67d969..3293a97 100644 --- a/everyday_wechat/utils/itchat_helper.py +++ b/everyday_wechat/utils/itchat_helper.py @@ -114,12 +114,13 @@ def init_wechat_config(): ats = [ats] if isinstance(ats, list): for at in ats: - times = TIME_COMPILE.findall(at) - if not times: + at = at.replace('-','-').replace(':',':') + start = at.split('-')[0].strip() + end = at.split('-')[1].strip() if len(at.split('-')) == 2 else start + if not (TIME_COMPILE.findall(start) and TIME_COMPILE.findall(end)): print('时间{}格式出错'.format(at)) continue - hour, minute = int(times[0][0]), int(times[0][1]) - temp_dict = {'hour': hour, 'minute': minute, 'uuid_list': uuid_list} + temp_dict = {'start': start, 'end': end, 'uuid_list': uuid_list} temp_dict.update(gi) alarm_dict[md5_encode(str(temp_dict))] = temp_dict # end---------------------------定时处理---------------------------end