0

I have two jobs in APScheduler which are executed by the cron trigger. The read job (get_value_job) reads a value from an external device and stores it in a variable. The write job (write_value) reads this value every minute and will write it to a text file. If both jobs run concurrently at second 0, the value of the write job will be outdated, because of a small delay in the read job. So the writing job should only start if the read job is finished and the value is actual.

My current code uses a flag and a while loop. Is there a better solution without a while loop to force write_value_job to wait until the value is updated?

class MyJob:
    value = 0
    finished = False

    def get_value(self):
        self.finished = False
        # This job will be blocked for a few seconds, because we request
        # an external device. Simulate it with delay of 5 seconds.
        time.sleep(5)
        self.value = 255
        self.finished = True
    
    def write_value(self):
        while not self.finished:
            time.sleep(0.1)
        my_value = self.value
        print(my_value)

if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    job = MyJob()
    scheduler.add_job(job.get_value, 'cron', id="get_value_job", second='*/10')
    scheduler.add_job(job.write_value, 'cron', id="write_value_job", minute='*/1')
    scheduler.start()
MSpiller
  • 3,500
  • 2
  • 12
  • 24
bluemarw
  • 3
  • 3
  • solved here https://stackoverflow.com/questions/54996869/apschedulertrigger-new-job-after-completion-of-previous-job – balderman Aug 08 '21 at 13:03
  • @balderman then it should be marked as a duplicate – gold_cy Aug 08 '21 at 13:06
  • 2
    Does this answer your question? [APScheduler:Trigger New job after completion of previous job](https://stackoverflow.com/questions/54996869/apschedulertrigger-new-job-after-completion-of-previous-job) – gold_cy Aug 08 '21 at 13:06
  • @balderman I've already found the question. In the question the job should be executed directly after the job is finished. For me the job should be executed depending on the state of read job and the time. So I would have to query the time in the listener function and decide whether the write job should be executed or not. Of course, this is a possible solution, but I thought it could be solved even more elegantly. – bluemarw Aug 08 '21 at 13:18

1 Answers1

0

You can customize scheduler running in one thread

sync_scheduler = BackgroundScheduler(
    executors={"default": ThreadPoolExecutor(1)}
)
Eazow
  • 21
  • 3