Run a function after a specific duration

Hello,

We are trying to write a Python function that is called after an hour from the current date. Based on the docs, frappe.enqueue is what we want to use to run this function in the background.

However, frappe.enqueue does not include a way to schedule the job.

For example:

frappe.enqueue(
    run_at=...    
)

Something like this is not available in frappe.enqueue.

Please advise if there is any other way to schedule a function to run after a specific duration.

Hi,

Scheduler Events

You can use Scheduler Events for running tasks periodically in the background using the scheduler_events hook.

app/hooks.py

scheduler_events = {
    "hourly": [
        # will run hourly
        "app.scheduled_tasks.update_database_usage"
    ],
}

app/scheduled_tasks.py

def update_database_usage():
    pass

Available Events

  • hourly, daily, weekly, and monthly

These events will trigger every hour, day, week, and month respectively.

  • hourly_long, daily_long, weekly_long, monthly_long

Same as above but these jobs are run in the long worker suitable for long-running jobs.

  • all

The all event is triggered every 4 minutes. This can be configured via the scheduler_interval key in common_site_config.json

  • cron

OR

you can create a DocType that specifies the exact time to run and use the all event type

docs: Background Jobs

Unfortunately this is not exactly what I want.

I don’t want a recurring schedule, I just want to run a function after a specific duration. For example one hour from now.

Frappe uses RQ as the underlying library for queuing jobs,

for example: frappe/frappe/core/doctype/rq_worker/rq_worker.py at develop · frappe/frappe · GitHub

RQ: Scheduling Jobs

Scheduling jobs are similarly easy:

# Schedule job to run at 9:15, October 10th
job = queue.enqueue_at(datetime(2019, 10, 8, 9, 15), say_hello)

# Schedule job to be run in 10 seconds
job = queue.enqueue_in(timedelta(seconds=10), say_hello)

docs: https://python-rq.org/