hub.eb?material_id=421&track_id=419

Preventing Scheduled Task Clashes


One caveat to running Scheduled Tasks is that it can be difficult to maintain consistency of data stored in a database. If multiple tasks are performing updates then changes may be overwritten.

The following example illustrates a race condition where the changes made by Task A may be lost:

  1. Task A fetches data from a resource.
  2. Task B fetches data from a resource.
  3. Task A makes local changes to the data.
  4. Task A updates the database.
  5. Task B makes local changes to the data.
  6. Task B updates the database.

The Lock Manager is used to lock resources to prevent multiple tasks using them concurrently. This can be employed to prevent multiple tasks updating the same resource and overwriting the changes of the other.

To ensure that Scheduled Tasks do not clash a common resource should be used and locks acquired using the Lock Manager. The following code snippet shows an example pattern:

// Before Form of Scheduled Task

// ID of resource to lock
var resourceId = "scheduledTaskResource";

// Get the instance of the Lock Manager
var lockManager = system.getLockManager();

// Generate a unique ID for this instance of the Scheduled Task
// A timestamp is unique enough for our purposes
var uid = new Date().valueOf();

// Try to acquired a lock on the resource.
// This returns false if it is already locked,
// indicating that another Scheduled Task is running
if (lockManager.lock(resourceId, uid)) {
  // Perform the task
  // ...
}

Current Module

Related