Web Development – How to Handle Time-Based Events in Web Application Backend

designweb-designweb-development

I'm currently working on design of small web service, and I have a following feature (simplified):

After some user actions, there is a wait period (ranging from 30sec to 40h) and after it's passed, the server should update database entry for the task, unless user cancelled it during the waiting period.
Executed task is quite simple, just a few calculations, but it must be delayed.

And I have no idea how to do this…

I know that similar situation happens in some browser based games, where you upgrade a building and get bonuses from it after it's finished, but I was unable to find how this feature is achieved. So, my question is, is there a "state-of-art" method of dealing with such problems in backend, or any method at all?

Best Answer

You can do this a few different ways. What you ultimately do depends on your server-side stack, your permissions on the server, and the nature of the side-effects needed for the delayed event.

As I see them, your options are:

  • An "embedded" scheduled task. If you're using a service-like backend technology (like a node server), you can put timeouts right in the application. And in some cases, as with node, you could even schedule a timeout for each individual event (if it turns out being more efficient than processing an event queue in your case).
  • A separate cron job, windows task, or backgrounded process, daemon, or service. A cron job should be able to execute up to once per minute. A windows task can execute up to every 5 minutes. A background job, daemon, or service can use sleeps/waits/timeouts to do things on even shorter intervals.
  • Client-driven event processing. If no side effects are required when the data isn't actively being used (e.g., all the users who care about the value are signed out), you can avoid the overhead and complexity of regularly "upkeep" jobs by just computing certain values and/or processing events as-needed during client requests. E.g., for each request from and about UserX, get entries from "the queue" where event_fire_time <= now and event_user = UserX, and "complete" those events.

In all scenarios, be sure to lock (with transactions if using a DBMS) the records your event code is processing.

Related Topic