调整定时任务运行方式,更新依赖

This commit is contained in:
lzybetter
2024-05-05 22:30:35 +08:00
parent 2c53584bec
commit 7dc397f833
4 changed files with 36 additions and 24 deletions

View File

@@ -7,7 +7,7 @@ if __name__ == "__main__":
## 初始化 ## 初始化
## flask初始化 ## flask初始化
app = Flask(__name__) app = Flask(__name__)
## 配初始化 ## 配初始化
config = Config() config = Config()
## 插件管理器 ## 插件管理器
manager = PluginManager(config) manager = PluginManager(config)

View File

@@ -1,6 +1,10 @@
aiofiles==23.2.1 aiofiles==23.2.1
aiohttp==3.9.5
aiosignal==1.3.1
anyio==4.3.0 anyio==4.3.0
APScheduler==3.10.4 APScheduler==3.10.4
async-timeout==4.0.3
attrs==23.2.0
blinker==1.7.0 blinker==1.7.0
certifi==2024.2.2 certifi==2024.2.2
cffi==1.16.0 cffi==1.16.0
@@ -11,6 +15,7 @@ exceptiongroup==1.2.1
Flask==3.0.3 Flask==3.0.3
Flask-APScheduler==1.13.1 Flask-APScheduler==1.13.1
Flask-Script==2.0.6 Flask-Script==2.0.6
frozenlist==1.4.1
greenlet==3.0.3 greenlet==3.0.3
greenletio==0.11.0 greenletio==0.11.0
h11==0.14.0 h11==0.14.0
@@ -24,6 +29,8 @@ idna==3.6
itsdangerous==2.1.2 itsdangerous==2.1.2
Jinja2==3.1.3 Jinja2==3.1.3
MarkupSafe==2.1.5 MarkupSafe==2.1.5
msal==1.27.0
multidict==6.0.5
priority==2.0.0 priority==2.0.0
pycparser==2.21 pycparser==2.21
PyJWT==2.8.0 PyJWT==2.8.0
@@ -44,3 +51,4 @@ urllib3==2.2.1
uvicorn==0.29.0 uvicorn==0.29.0
Werkzeug==3.0.2 Werkzeug==3.0.2
wsproto==1.2.0 wsproto==1.2.0
yarl==1.9.4

View File

@@ -2,7 +2,7 @@ import asyncio
import importlib.util import importlib.util
import os import os
import threading import threading
from datetime import datetime from datetime import datetime, timedelta
from util.base_plugin import BasePlugin from util.base_plugin import BasePlugin
@@ -47,10 +47,10 @@ class PluginManager:
print(f"Executing plugin '{plugin_name}':") print(f"Executing plugin '{plugin_name}':")
plugin_instance.run_plugin(self.callback, *args, **kwargs) plugin_instance.run_plugin(self.callback, *args, **kwargs)
def execute_plugin(self, plugin_name, *args, **kwargs): async def execute_plugin(self, plugin_name, *args, **kwargs):
if plugin_name in self.plugins: if plugin_name in self.plugins:
print(f"Executing plugin '{plugin_name}':") print(f"Executing plugin '{plugin_name}':")
return self.plugins[plugin_name].run_plugin(self.callback, *args, **kwargs) return await self.plugins[plugin_name].run_plugin(*args, **kwargs)
else: else:
print(f"Plugin '{plugin_name}' not found.") print(f"Plugin '{plugin_name}' not found.")
@@ -60,15 +60,6 @@ class PluginManager:
return [plugin[0] for plugin in self.plugins.items()] return [plugin[0] for plugin in self.plugins.items()]
def callback(self, result):
print(f"Plugin '{result['plugin_name']}' returned:")
print(f"Success: {result['success']}")
if result['success']:
print(f"Result: {result['result']}")
else:
print(f"Error: {result['error']}")
def start_scheduler(self): def start_scheduler(self):
self.loop = asyncio.new_event_loop() self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop) asyncio.set_event_loop(self.loop)
@@ -87,26 +78,40 @@ class PluginManager:
async def execute_plugin_async(self, plugin_name, schedule, *args, **kwargs): async def execute_plugin_async(self, plugin_name, schedule, *args, **kwargs):
sleep_time = 30
while True: while True:
if plugin_name in self.plugins: if plugin_name in self.plugins:
print(f"Executing plugin '{plugin_name}':") print(f"Executing plugin '{plugin_name}':")
print(schedule)
if schedule['mode'] == "INTERVAL" or schedule['mode'] == "CONTIENUOUS": if schedule['mode'] == "INTERVAL" or schedule['mode'] == "CONTIENUOUS":
result = self.execute_plugin(plugin_name, *args, **kwargs) result = await self.execute_plugin(plugin_name, *args, **kwargs)
token = self.config.get_config('TELEGRAM')['BOT_TOKEN'] token = self.config.get_config('TELEGRAM')['BOT_TOKEN']
chat_id = self.config.get_config('TELEGRAM')['CHAT_ID'] chat_id = self.config.get_config('TELEGRAM')['CHAT_ID']
await self.send_message_async(token, chat_id, result) await self.send_message_async(token, chat_id, result['result'])
sleep_time = schedule['INTERVAL_TIME']
elif schedule['mode'] == "FIX": elif schedule['mode'] == "FIX":
now = datetime.now() now = datetime.now()
if now.hour == schedule['HOUR'] and now.minute == schedule['MINUTE']: today = now.date()
result = self.execute_plugin(plugin_name, *args, **kwargs) if now.hour <= schedule['HOUR'] and now.minute <= schedule['MINUTE']:
next_day = today
else:
next_day = today + timedelta(days=1)
next_time = datetime(year=next_day.year, month=next_day.month, day=next_day.day,
hour=schedule['HOUR'], minute=schedule['MINUTE'])
print(next_time)
sleep_time = (next_time - now).seconds
if now.hour == schedule['HOUR'] and now.minute == schedule["MINUTE"]:
result = await self.execute_plugin(plugin_name, *args, **kwargs)
token = self.config.get_config('TELEGRAM')['BOT_TOKEN'] token = self.config.get_config('TELEGRAM')['BOT_TOKEN']
chat_id = self.config.get_config('TELEGRAM')['CHAT_ID'] chat_id = self.config.get_config('TELEGRAM')['CHAT_ID']
await self.send_message_async(token, chat_id, result) await self.send_message_async(token, chat_id, result['result'])
else: else:
print(f"Plugin '{plugin_name}' not found.") print(f"Plugin '{plugin_name}' not found.")
print(schedule) print(sleep_time)
await asyncio.sleep(schedule['INTERVAL_TIME']) await asyncio.sleep(sleep_time)
async def send_message_async(self, bot_token, chat_id, text): async def send_message_async(self, bot_token, chat_id, text):
@@ -119,7 +124,6 @@ class PluginManager:
try: try:
schedule_config = self.config.get_plugin_config('SCHEDULE', self.plugins_path[plugin_name]) schedule_config = self.config.get_plugin_config('SCHEDULE', self.plugins_path[plugin_name])
mode = schedule_config['MODE'].upper() mode = schedule_config['MODE'].upper()
print(mode)
schedule['mode'] = mode schedule['mode'] = mode
if mode == 'INTERVAL': if mode == 'INTERVAL':
if 'INTERVAL_TIME' in schedule_config.keys(): if 'INTERVAL_TIME' in schedule_config.keys():
@@ -133,8 +137,8 @@ class PluginManager:
else: else:
schedule['INTERVAL_TIME'] = 30 schedule['INTERVAL_TIME'] = 30
elif mode == 'FIX' and "RUN_TIME" in schedule_config.keys(): elif mode == 'FIX' and "RUN_TIME" in schedule_config.keys():
schedule['HOUR'] = schedule_config["RUN_TIME"]['HOUR'] schedule['HOUR'] = int(schedule_config["RUN_TIME"]['HOUR'])
schedule['MINUTE'] = schedule_config["RUN_TIME"]['MINUTE'] schedule['MINUTE'] = int(schedule_config["RUN_TIME"]['MINUTE'])
schedule['INTERVAL_TIME'] = 30 schedule['INTERVAL_TIME'] = 30
elif mode == 'CONTIENUOUS': elif mode == 'CONTIENUOUS':
schedule['INTERVAL_TIME'] = 30 schedule['INTERVAL_TIME'] = 30

View File

@@ -3,5 +3,5 @@ class BasePlugin:
self.plugin_name = plugin_name self.plugin_name = plugin_name
self.title = title self.title = title
def run_plugin(self, callback): def run_plugin(self):
raise NotImplementedError("Subclasses must implement run_plugin method") raise NotImplementedError("Subclasses must implement run_plugin method")