首页 > 解决方案 > 将对象作为函数的参数传递给作业调度程序

问题描述

我尝试使用 apscheduler 将对象作为参数传递给作业函数。这很好,但在我的情况下,我想更改它的一个值并在触发作业时使用更新的值。这是我的示例代码

import time
import sqlalchemy
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore


class MyClass:
    def __init__(self, *args, **kwargs):
        self.state = kwargs.get('state', "")


jobstores = {
    'default': SQLAlchemyJobStore(url='sqlite:///sched.db', tablename='apscheduler_jobs')
}

scheduler = BackgroundScheduler()
scheduler.configure(timezone='Europe/Paris')
scheduler.add_jobstore(jobstores['default'], 'default')


def myFunction(_internals):
    print("- in job")
    print(_internals.__dict__)
    print(".")


if __name__ == "__main__":
    scheduler.start()
    myInstance = MyClass(state="off")
    print(myInstance.__dict__)
    j1 = scheduler.add_job(myFunction, trigger='cron', args=[myInstance],  second='*/10', max_instances=10, jobstore='default', srv_id="blablabla-x6548710")
    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
            myInstance.__setattr__("state", "running")
            print(myInstance.__dict__)
    except (KeyboardInterrupt, SystemExit):
        print('exit')
        scheduler.shutdown()

这是我的期望:

{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
in job
{'state': 'running'}
.
{'state': 'running'}

但相反,我有:

{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
in job
{'state': 'off'}
.
{'state': 'running'}

有没有办法在 while 循环和触发这个时的作业中具有相同的值?

谢谢男孩女孩

标签: python-3.xapscheduler

解决方案


原来,工作中的 myInstance 是一个完全不同的对象。因此,它不受循环中所做的任何更改的影响。我使用了另一种策略:使用 memcached 在循环和计划作业之间进行通信。仍然对任何其他建议持开放态度。


推荐阅读