1+ import importlib
12import json
23from asyncio import iscoroutinefunction
34from datetime import datetime , timedelta
4- from typing import Optional , Union
5+ from typing import Any , Callable , Optional , Union
56
67from apscheduler .events import EVENT_ALL , SchedulerEvent
78from apscheduler .executors .asyncio import AsyncIOExecutor
@@ -152,6 +153,18 @@ async def close_system_scheduler(cls) -> None:
152153 scheduler .shutdown ()
153154 logger .info ('✅️ 关闭定时任务成功' )
154155
156+ @classmethod
157+ def _import_function (cls , func_path : str ) -> Callable [..., Any ]:
158+ """
159+ 动态导入函数
160+
161+ :param func_path: 函数字符串,如module_task.scheduler_test.job
162+ :return: 导入的函数对象
163+ """
164+ module_path , func_name = func_path .rsplit ('.' , 1 )
165+ module = importlib .import_module (module_path )
166+ return getattr (module , func_name )
167+
155168 @classmethod
156169 def get_scheduler_job (cls , job_id : Union [str , int ]) -> Job :
157170 """
@@ -172,12 +185,12 @@ def add_scheduler_job(cls, job_info: JobModel) -> None:
172185 :param job_info: 任务对象信息
173186 :return:
174187 """
175- job_func = eval (job_info .invoke_target )
188+ job_func = cls . _import_function (job_info .invoke_target )
176189 job_executor = job_info .job_executor
177190 if iscoroutinefunction (job_func ):
178191 job_executor = 'default'
179192 scheduler .add_job (
180- func = eval ( job_info . invoke_target ) ,
193+ func = job_func ,
181194 trigger = MyCronTrigger .from_crontab (job_info .cron_expression ),
182195 args = job_info .job_args .split (',' ) if job_info .job_args else None ,
183196 kwargs = json .loads (job_info .job_kwargs ) if job_info .job_kwargs else None ,
@@ -198,15 +211,15 @@ def execute_scheduler_job_once(cls, job_info: JobModel) -> None:
198211 :param job_info: 任务对象信息
199212 :return:
200213 """
201- job_func = eval (job_info .invoke_target )
214+ job_func = cls . _import_function (job_info .invoke_target )
202215 job_executor = job_info .job_executor
203216 if iscoroutinefunction (job_func ):
204217 job_executor = 'default'
205218 job_trigger = DateTrigger ()
206219 if job_info .status == '0' :
207220 job_trigger = OrTrigger (triggers = [DateTrigger (), MyCronTrigger .from_crontab (job_info .cron_expression )])
208221 scheduler .add_job (
209- func = eval ( job_info . invoke_target ) ,
222+ func = job_func ,
210223 trigger = job_trigger ,
211224 args = job_info .job_args .split (',' ) if job_info .job_args else None ,
212225 kwargs = json .loads (job_info .job_kwargs ) if job_info .job_kwargs else None ,
0 commit comments