# -- coding: utf-8 --
"""
@Name: timers.py
@Auth: os-pangzw
@Date: 2022/6/22-10:15
@Desc:
@Ver : 0.0.0
"""
import datetime
import time
from threading import Thread
from time import sleep
from log import get_logger
logger = get_logger()
class TaskTimer:
__instance = None
def __new__(cls, *args, **kwargs):
"""
单例模式
"""
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self):
if not hasattr(self, 'task_queue'):
setattr(self, 'task_queue', [])
if not hasattr(self, 'is_running'):
setattr(self, 'is_running', False)
def write_log(self, level, msg):
cur_time = datetime.datetime.now()
with open('./task.log', mode='a+', encoding='utf8') as file:
s = "[" + str(cur_time) + "][" + level + "] " + msg
print(s)
file.write(s + "\n")
def work(self):
"""
处理任务队列
"""
while True:
for task in self.task_queue:
if task['interval']:
self.cycle_task(task)
elif task['timing']:
self.timing_task(task)
sleep(5)
def cycle_task(self, task):
"""
周期任务
"""
if task['next_sec'] <= int(time.time()):
try:
task['fun'](*task['arg'])
# self.write_log("正常", "周期任务:" + task['fun'].__name__ + " 已执行")
logger.info(f"任务已执行 {task['fun'].__name__}")
except Exception as e:
# self.write_log("异常", "周期任务:" + task['fun'].__name__ + " 函数内部异常:" + str(e))
logger.error(f"任务执行异常 {task['fun'].__name__}")
finally:
task['next_sec'] = int(time.time()) + task['interval']
def timing_task(self, task):
"""
定时任务
"""
# 今天已过秒数
today_sec = self.get_today_until_now()
# 到了第二天,就重置任务状态
if task['today'] != self.get_today():
task['today'] = self.get_today()
task['today_done'] = False
# 第一次执行
if task['first_work']:
if today_sec >= task['task_sec']:
task['today_done'] = True
task['first_work'] = False
else:
task['first_work'] = False
# 今天还没有执行
if not task['today_done']:
if today_sec >= task['task_sec']: # 到点了,开始执行任务
try:
task['fun'](*task['arg'])
# self.write_log("正常", "定时任务:" + task['fun'].__name__ + " 已执行")
logger.info(f"任务已执行 {task['fun'].__name__}")
except Exception as e:
# self.write_log("异常", "定时任务:" + task['fun'].__name__ + " 函数内部异常:" + str(e))
logger.error(f"任务执行异常 {task['fun'].__name__}")
finally:
task['today_done'] = True
if task['first_work']:
task['first_work'] = False
def get_today_until_now(self):
"""
获取今天凌晨到现在的秒数
"""
i = datetime.datetime.now()
return i.hour * 3600 + i.minute * 60 + i.second
def get_today(self):
"""
获取今天的日期
"""
i = datetime.datetime.now()
return i.day
def join_task(self, fun, arg, interval=None, timing=None):
"""
interval和timing只能存在1个
:param fun: 你要调用的任务
:param arg: fun的参数
:param interval: 周期任务,单位秒
:param timing: 定时任务,取值:[0,24)
"""
# 参数校验
if (interval != None and timing != None) or (interval == None and timing == None):
raise Exception('interval和timing只能选填1个')
if timing and not 0 <= timing < 24:
raise Exception('timing的取值范围为[0,24)')
if interval and interval < 5:
raise Exception('interval最少为5')
# 封装一个task
task = {
'fun': fun,
'arg': arg,
'interval': interval,
'timing': timing,
}
# 封装周期或定时任务相应的参数
if timing:
task['task_sec'] = timing * 3600
task['today_done'] = False
task['first_work'] = True
task['today'] = self.get_today()
elif interval:
task['next_sec'] = int(time.time()) + interval
# 把task加入任务队列
self.task_queue.append(task)
# self.write_log("正常", "新增任务:" + fun.__name__)
logger.info(f"新增定时任务 {fun.__name__}")
def start(self):
"""
开始执行任务
返回线程标识符
"""
if not self.is_running:
thread = Thread(target=self.work)
thread.start()
self.is_running = True
# self.write_log("正常", "TaskTimer已开始运行!")
logger.info(f"任务运行开始")
return thread.ident
# self.write_log("警告", "TaskTimer已运行,请勿重复启动!")
logger.info(f"任务运行中")
if __name__ == '__main__':
pass
没有合适的资源?快使用搜索试试~ 我知道了~
alert_sending
共51个文件
sample:13个
py:8个
pyc:5个
需积分: 9 0 下载量 197 浏览量
2022-08-31
18:08:08
上传
评论
收藏 44KB RAR 举报
温馨提示
alert_sending
资源详情
资源评论
资源推荐
收起资源包目录
alert_sending.rar (51个子文件)
alert_sending
timers.py 6KB
log_sqlalchemy.py 4KB
main.py 2KB
logs
alert_log_20220831.log 13KB
.git
index 792B
hooks
fsmonitor-watchman.sample 5KB
pre-push.sample 1KB
prepare-commit-msg.sample 1KB
pre-merge-commit.sample 416B
applypatch-msg.sample 478B
pre-commit.sample 2KB
pre-receive.sample 544B
pre-applypatch.sample 424B
commit-msg.sample 896B
pre-rebase.sample 5KB
update.sample 4KB
post-update.sample 189B
push-to-checkout.sample 3KB
config 130B
description 73B
refs
tags
heads
objects
e6
9de29bb2d1d6434b8b29ae775ad8c2e48c5391 15B
1a
14af77f3f32d2fad4cb6d06683d031fe3e704d 1KB
34
68039749608096e101f0113a4f5b32d1897dcd 141B
info
77
5b15c22bf516fd9d28dc32ea12013da67c46ab 140B
pack
f6
0879030fb7abd0f9f960449cdf85ef5126872e 767B
38
749ca9cee8238489687a790e2ed48e4de71cd6 143B
22
c55664c9718754b15938199f8f5cea7c9a63fe 1KB
28
7af7639f17f8b75109e84f16b09e32d293e8f0 1KB
e8
dde1ddc828e2cc41d1b82f2a8677bb4da57f17 111B
6f
0535fe0bb0ea39e4a660b14f9b4ce9861389a0 2KB
info
exclude 240B
HEAD 47B
__pycache__
log.cpython-38.pyc 1KB
main.cpython-38.pyc 1KB
model.cpython-38.pyc 2KB
dbSession.cpython-38.pyc 3KB
config.cpython-38.pyc 2KB
.idea
ZeppelinRemoteNotebooks
misc.xml 188B
vcs.xml 185B
modules.xml 285B
alert_sending.iml 405B
workspace.xml 8KB
.gitignore 241B
inspectionProfiles
profiles_settings.xml 174B
config.yml 1KB
dbSession.py 3KB
alert_request.py 3KB
model.py 2KB
.gitignore 146B
log.py 2KB
config.py 2KB
共 51 条
- 1
Pang文
- 粉丝: 134
- 资源: 15
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0