将对象作为函数的参数传递给作业助手

问题描述 投票:0回答:1

我尝试使用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.x apscheduler
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.