Sunday, 4 December 2022

Running cron job on flask between 9 am to 3 pm at an interval of 5 minutes

 To run a cron job on a Flask app between 9 am and 3 pm at an interval of 5 minutes, you can use the Flask-APScheduler package to schedule the cron job. The Flask-APScheduler package is a Flask extension that adds support for the APScheduler package, which is a Python library for scheduling tasks. Here is an example of how to use the Flask-APScheduler package to run a cron job on a Flask app between 9 am and 3 pm at an interval of 5 minutes:

  1. Install the Flask-APScheduler and APScheduler packages using the pip package manager.
pip install Flask-APScheduler APScheduler
  1. Import the Flask-APScheduler and APScheduler modules in your Flask app.
from flask_apscheduler import APScheduler
from apscheduler.triggers.cron import CronTrigger
  1. Create an instance of the APScheduler class and configure the cron job.
# create an instance of the APScheduler class
scheduler = APScheduler()

# define the cron job
cron = {
    'id': 'my_cron_job',
    'func': 'my_cron_function',
    'args': (),
    'trigger': CronTrigger(hour='9-15', minute='*/5'),
}

# add the cron job to the scheduler
scheduler.add_job(**cron)

  1. Initialize the scheduler and start the cron job.
# initialize the scheduler 
scheduler.init_app(app) # start the cron job scheduler.start()

This will run the my_cron_function function defined in your Flask app every 5 minutes between 9 am and 3 pm, according to the CronTrigger specified in the cron job configuration. You can modify the CronTrigger to schedule the cron job at different times and intervals. You can also specify the time zone for the cron job using the timezone parameter in the CronTrigger constructor.

# specify the time zone for the cron job 
CronTrigger(hour='9-15', minute='*/5', timezone='Asia/Kolkata')

This will run the cron job at the specified times and intervals using the time zone specified in the timezone parameter. You can use the Flask-APScheduler package to easily add cron jobs to your Flask app and schedule them to run at specific times and intervals. You can also use the APScheduler package to schedule other types of tasks, such as periodic tasks or tasks that run only once.

No comments:

Post a Comment