Skip to content
Advertisement

Thread error while running scheduled task inside of a Flask application

I want to create a scheduler that will run every hour in my Flask application. To do this, I use the APScheduler library. Here is the most basic source code I could find online:

from apscheduler.scheduler import Scheduler
import atexit

cron = Scheduler(daemon=True)
cron.start()

@cron.interval_schedule(minutes=1)
def job_function():
    print("Hi")

atexit.register(lambda: cron.shutdown(wait=False))

When I try to run my application, I get the following error:

Traceback (most recent call last):
  File "/home/dimitar/Desktop/dev/Tradiebot/local/WorxManager/backend/Server/app.py", line 31, in <module>
    def job_function():
  File "/usr/lib/python3.9/site-packages/apscheduler/scheduler.py", line 405, in inner
    func.job = self.add_interval_job(func, **options)
  File "/usr/lib/python3.9/site-packages/apscheduler/scheduler.py", line 347, in add_interval_job
    return self.add_job(trigger, func, args, kwargs, **options)
  File "/usr/lib/python3.9/site-packages/apscheduler/scheduler.py", line 285, in add_job
    if not self.running:
  File "/usr/lib/python3.9/site-packages/apscheduler/scheduler.py", line 148, in running
    thread_alive = self._thread and self._thread.isAlive()
AttributeError: 'Thread' object has no attribute 'isAlive'

After a bit of research, I found that other people on python 3.9 have experienced a similar issue, but I found no solution to the problem.

I do not want to downgrade my python version in fear that it will effect other libraries I am using as some of them are new and not developed to run on older versions of python.

Is there a workaround or an alternative library I can use to schedule a task to run in specified time intervals on a flask application?

Advertisement

Answer

That code looks like it belongs to APScheduler 2.x which has not been updated in 7 years. Upgrade and the problem goes away.

Advertisement