[英]APScheduler how to add job outside the scheduler?
我有一個簡單的要求。 我正在運行apscheduler作為一個單獨的進程。 我有另一個jobproducer腳本,我希望將作業添加到調度程序並運行它。
這是我的調度程序代碼,
# appsched.py
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
scheduler.start()
這是我的作業制作人腳本,
# jobproducer.py
from appsched import scheduler
def say_hello_job():
print "Hello"
scheduler.add_job(say_hello_job, 'interval', minutes=1)
不用說,這不起作用。 有沒有辦法通過使用jobstore來完成這項工作? 如何與多個不同的職位生產者共享調度程序?
我有一個類似的問題,我的調度程序進程是一個uWSGI MULE進程,並且有一個單獨的應用程序,我想添加新的作業。
查看BaseScheduler的add_job()
函數:
with self._jobstores_lock:
if not self.running:
self._pending_jobs.append((job, jobstore, replace_existing))
self._logger.info('Adding job tentatively -- it will be properly scheduled when the scheduler starts')
else:
self._real_add_job(job, jobstore, replace_existing, True)
您可以看到問題:調度程序僅在已啟動時添加作業。
幸運的是,解決方案非常簡單,我們應該定義自己的“ 僅添加作業 ”調度程序:
class JobAddScheduler(BlockingScheduler):
def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined,
coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default',
executor='default', replace_existing=False, **trigger_args):
job_kwargs = {
'trigger': self._create_trigger(trigger, trigger_args),
'executor': executor,
'func': func,
'args': tuple(args) if args is not None else (),
'kwargs': dict(kwargs) if kwargs is not None else {},
'id': id,
'name': name,
'misfire_grace_time': misfire_grace_time,
'coalesce': coalesce,
'max_instances': max_instances,
'next_run_time': next_run_time
}
job_kwargs = dict((key, value) for key, value in six.iteritems(job_kwargs) if value is not undefined)
job = Job(self, **job_kwargs)
# Add jobs to job store
with self._jobstores_lock:
self._real_add_job(job, jobstore, replace_existing, True)
return job
def start(self):
pass
def shutdown(self, wait=True):
pass
def _main_loop(self):
pass
def wakeup(self):
pass
然后我們可以即時添加cron作業:
jobscheduler = JobAddScheduler()
jobscheduler.add_job(...)
不要忘記配置調度程序! 在我的例子中,我使用SQLAlchemy-MySQL后端來存儲作業:
jobstores=dict(default=SQLAlchemyJobStore(url='mysql+pymsql://USER:PASSWORD@SERVER/DATABASE'))
jobscheduler.configure(jobstores=jobstores)
我不確定其他的求職店,但是在我添加了一份新工作之后,我不得不調用單獨的調度程序進程的wakeup()
函數來“激活”該作業。 我使用uWSGI的信號系統實現了這一目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.