0

In eCommerce application, my requirement is, after placing the order send a notification(execute a method) to the seller after two hours.

What is the best way to automatically execute the method after 2 hours.?

Mohammad Aarif
  • 1,619
  • 13
  • 19

3 Answers3

0

You can use celery to run tasks after a certain delay.

You can read more about it here

http://docs.celeryproject.org/en/master/userguide/calling.html#eta-and-countdown

at14
  • 1,194
  • 9
  • 16
0

This will work for python3.

If you are familiar with asyncio you can use the event loop call_later function.

Event loop

loop.call_later(delay, callback, *args, context=None)

Schedule callback to be called after the given delay number of seconds (can be either an int or a float).

An instance of asyncio.TimerHandle is returned which can be used to cancel the callback.

callback will be called exactly once. If two callbacks are scheduled for exactly the same time, the order in which they are called is undefined.

The optional positional args will be passed to the callback when it is called. If you want the callback to be called with keyword arguments use functools.partial().

An optional keyword-only context argument allows specifying a custom contextvars.Context for the callback to run in. The current context is used when no context is provided.

Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.

Changed in version 3.8: In Python 3.7 and earlier with the default event loop implementation, the delay could not exceed one day. This has been fixed in Python 3.8.

Example (Source):

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.get_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
Amiram
  • 1,227
  • 6
  • 14
0

In my production code I prefer APScheduler over Celery because it provides lots of settings on running jobs with specific delay or at specific date (so you can just add timedelta(hours=2) to you datetime.utcnow())

Take a look at it: https://apscheduler.readthedocs.io/en/stable/

Alveona
  • 850
  • 8
  • 17