Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16743

How to Schedule Async Coroutine Functions with APScheduler?

$
0
0

I am developing a service in Python to send automated emails and am facing challenges with scheduling asynchronous coroutine functions using APScheduler. The service is built with FastAPI to handle user inputs and aiomysql for asynchronous database operations. My goal is to schedule email sending tasks that involve asynchronous database calls.

Here's the setup for my APScheduler within the application:

from apscheduler.schedulers.asyncio import AsyncIOSchedulerfrom apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStorefrom apscheduler.executors.pool import ThreadPoolExecutorclass APScheduler:    jobstores = {'default': SQLAlchemyJobStore(url='mysql+pymysql://USER:PASSWORD@HOST/DATABASE')    }    executors = {'default': ThreadPoolExecutor(5)    }    def __init__(self):        self._scheduler = AsyncIOScheduler(jobstores=self.jobstores, executors=self.executors)        self._logger = create_logger("Scheduler")        self.exchange_state = ExchangeStateMachine()    def schedule_email(self, schedule_time, bot, contact, subject, email_body, campaign_id, thread_id=None, reply_id=None, attachments=[]):        self._scheduler.add_job(            self.exchange_state.send_email, 'date', run_date=schedule_time,            kwargs={'bot': bot, 'contact': contact, 'subject': subject, 'email_body': email_body, 'campaign_id': campaign_id, 'thread_id': thread_id, 'reply_id': reply_id, 'attachments': attachments},            id=f"send-email-{bot.id}-{contact.id}-{campaign_id}",            replace_existing=True        )        self._logger.info(f"Email scheduled: To {contact.email} from {bot.email} at {schedule_time}.")

The ExchangeStateMachine.send_email method, intended for scheduling, includes several asynchronous database operations:

class ExchangeStateMachine:    async def send_email(self, bot, contact, subject, email_body, campaign_id, thread_id=None, reply_id=None, attachments=[]):        # Asynchronous operations here        self._logger.info("Send email callback invoked.")

However, attempting to schedule this coroutine results in a traceback indicating that the coroutine was never awaited:

RuntimeWarning: coroutine 'ExchangeStateMachine.send_email' was never awaitedRuntimeWarning: Enable tracemalloc to get the object allocation traceback

I tried capturing the asyncio event loop at the start of the FastAPI application and passing it to the APScheduler or directly to the job function, using asyncio.run_coroutine_threadsafe to schedule the coroutine.

Despite these efforts, I continue to encounter the "coroutine was never awaited" warning, and I'm unsure how to proceed to correctly schedule and execute asynchronous coroutine functions with APScheduler.

How can I properly schedule and execute async coroutine functions with APScheduler?


Viewing all articles
Browse latest Browse all 16743

Trending Articles