Search code examples
pythonpython-3.xclassselfapscheduler

Self references several different objects instead of one


I have a class with a method that creates schedules (it is simplified for the sake of, well, simplicity):

def create_schedule(self):
    # Create a function-1 event
    scheduler.add_job(self.function_1,
                      trigger='date',
                      run_date=datetime_1,
                      args=[self])

    # Create a function-2 event
    scheduler.add_job(self.function_2,
                      trigger='date',
                      run_date=datetime_2,
                      args=[self])

And these are the class function_1 and function_2 methods:

def function_1(self, *args):
    print('self in function_1:', self)

def function_2(self, *args):
    print('self in function_2:', self)

For some reason, when it executes both events from the scheduler, the following is printed:

self in function_1: <program.my_class object at 0x6f03e430>
self in function_2: <program.my_class object at 0x6f03e4b0>

i.e. the two are different objects, and thus changes made by function_1 will not appear in function_2 and vice-versa.

Why is that? Shouldn't all instances pointed by self be the same? Is there a way to circumvent this and force all selfs to actually point at the same instance?


Solution

  • You registered two different events with apscheduler, which in your configuration stores your event callback information in a database in a serialized form:

    Job stores house the scheduled jobs. The default job store simply keeps the jobs in memory, but others store them in various kinds of databases. A job’s data is serialized when it is saved to a persistent job store, and deserialized when it’s loaded back from it.

    Bold emphasis mine.

    The two jobs you have are executed independently, so they were deserialized independently leading to two new instances being created from the serialized data.

    You can't count on separate events to act on the same instance. You'll need to externalize your state, by adding enough identifying information to recreate the state when the job fires.