Recurring Timer

    +

    Goal: Demonstrate a recurring Eventing Timer.

    Implementation: Create a JavaScript function that contains an OnUpdate handler and a Timer callback function. The handler listens for mutations or data-changes within a specified, source bucket. When any document within the bucket is created or modified, the handler creates a callback in the future to execute a user-defined routine. In this example, we rely on a control document which if the created or altered controls whether a Recurring Timer will be created or canceled.

    • Test 1: The control document is created or mutated in such a way that a Timer is created and fires approximately 30 seconds in the future, at which point a document representing user work is written to the source bucket with the scheduled time of execution. The original control document, in the source bucket, is not changed. The Timer is re-armed and will execute again until canceled.

    • Test 2: The control document mutated in such a way that any existing Timer with the reference of the control documents id (meta.id) is canceled. This has no effect if the Timer created has already fired.

    Preparations (Common)

    For this example, two buckets 'source' and 'metadata', are required (note the metadata bucket for Eventing can be shared with other Eventing functions). Make both buckets with minimum size of 100MB.

    For steps to create buckets, see Create a Bucket.

    The 'metadata' bucket is for the sole use of the Eventing system, do not add, modify, or delete documents from this bucket. In addition do not drop or flush or delete the bucket while you have any deployed Eventing functions.

    Setup:

    1. Access the Couchbase Web Console > Buckets page.

      • You should see the following once you have created your buckets:

        recurring timer 01 buckets
    2. Click the Documents link of the source bucket.

      • You should see no user records.

        recurring timer 01 documents
      • Click Add Document in the upper right banner.

      • In the Add Document dialog, specify the name recurring_timer::1 as the New Document ID.

        recurring timer 01 add document
      • Click Save.

      • In the Edit Document dialog, the following text is displayed:

        {
        "click": "to edit",
        "with JSON": "there are no reserved field names"
        }
      • Replace the above text with the following JSON document via copy and paste:

        {
          "type": "recurring_timer",
          "id": 1,
          "active": false
        }
        recurring timer 01 docdata
      • Click Save.

    3. From the Couchbase Web Console > Eventing page, click ADD FUNCTION, to add a new Function. The ADD FUNCTION dialog appears.

    4. In the ADD FUNCTION dialog, for individual Function elements provide the below information:

      • For the Source Bucket drop-down, select source.

      • For the Metadata Bucket drop-down, select metadata.

      • Enter recurring_timer as the name of the Function you are creating in the Function Name text-box.

      • [Optional Step] Enter text Explore recurring timers, in the Description text-box.

      • For the Settings option, use the default values.

      • For the Bindings option, add just one bindings.

        • For the binding, select the "bucket alias", specify src_bkt as the "alias name" of the bucket, select source as the associated bucket, and select "read and write".

      • After configuring your settings your screen should look like this:

        recurring timer 01 settings
    5. After providing all the required information in the ADD FUNCTION dialog, click Next: Add Code. The recurring_timer dialog appears.

      • The recurring_timer dialog initially contains a placeholder code block. You will substitute your actual recurring_timer code in this block.

        recurring timer 02 editor with default
      • Copy the following Function, and paste it in the placeholder code block of recurring_timer dialog.

        function CreateRecurringTimer(context) {
            log('From CreateRecurringTimer: creating timer', context.mode, context.id);
            // Create a timestamp 30 seconds from now
            var thirtySecFromNow = new Date(); // Get current time & add 30 sec. to it.
            thirtySecFromNow.setSeconds(thirtySecFromNow.getSeconds() + 30);
            // Create a document to use as out for our context
            createTimer(RecurringTimerCallback, thirtySecFromNow, context.id, context);
        }
        
        function RecurringTimerCallback(context) {
            log('From RecurringTimerCallback: timer fired', context);
            // do any sort of recurring work here, just update a date_stamp in a doc
            src_bkt["cur_" + context.id] = { "last_update": new Date() };
            // rearm the timer
            CreateRecurringTimer({ "id": context.id, "mode": "via_callback" })
        }
        
        function OnUpdate(doc, meta) {
            // You would typically filter to mutations of interest
            if (doc.type !== 'recurring_timer') return;
            if (doc.active === false) {
                if (cancelTimer(RecurringTimerCallback, meta.id)) {
                    log('From OnUpdate: canceled active Timer, doc.active', doc.active, meta.id);
                } else {
                    log('From OnUpdate: no active Timer to cancel, doc.active', doc.active, meta.id);
                }
            } else {
                log('From OnUpdate: create/overwrite doc.active', doc.active, meta.id);
                CreateRecurringTimer({  "id": meta.id, "mode": "via_onupdate" });
            }
        }

        After pasting, the screen appears as displayed below:

        recurring timer 03 editor with code
      • Click Save.

      • To return to the Eventing screen, click the '< back to Eventing' link (below the editor) or click Eventing tab.

    6. The OnUpdate routine specifies that when a change occurs to data within the bucket, actions will be processed according to the field within the document. First we ignore all documents that do not have a doc.type of "recurring_timer" — this is the control document. Next we use the field "active" to determine which action we take.

      • If "active" is true we will create a series of Timers that will fire approximately 30 seconds in the future.

      • If "active" is false we will cancel the existing Timer if any.

      • In the event a Timer created by this Function fires, the callback RecurringTimerCallback executes, and will write a new document with a similar key (but with "cur_" prepended) into the "source" bucket.

    7. From the Eventing screen, click Deploy.

      • In the Confirm Deploy Function dialog, select Everything from the Feed boundary option.

      • Click Deploy Function.

    8. The Eventing function is deployed and starts running within a few seconds. From this point, the defined Function is executed on all existing documents, and more importantly it will also run on subsequent mutations.

    Test 1: Create a Recurring Timer and allow the Timer to Fire and Rearm

    1. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document recurring_timer::1 — it should look like this:

        {
          "type": "recurring_timer",
          "id": 1,
          "active": false
        }

        Change "active" to true, then click Save. This will create a mutation and the Function will generate the first of a series of recurring Timers. The control document is now:

        {
          "type": "recurring_timer",
          "id": 1,
          "active": true
        }
    2. Access the Couchbase Web Console > Eventing page and if necessary select the Function recurring_timer, then click the "Log" link for Deployed Function to view the activity.

      • Here we see from the Application log that we created a timer. Note the log is in reverse order and the bottom (or first) message was a NOOP because doc.active was false when we first deployed and we tried to cancel any timer if it was running.

        2020-08-06T09:34:24.073-07:00 [INFO] "From CreateRecurringTimer: creating timer" "via_onupdate" "recurring_timer::1"
        2020-08-06T09:34:24.073-07:00 [INFO] "From OnUpdate: create/overwrite doc.active" true "recurring_timer::1"
        2020-08-06T09:05:52.749-07:00 [INFO] "From OnUpdate: no active Timer to cancel, doc.active" false "recurring_timer::1"
        recurring timer 04 log active1
    3. Close the Function Log dialog, then wait about 2 minutes and click the "Log" link for Deployed Function recurring_timer to view the activity again.

      • Here we see the timer fired and executed the callback RecurringTimerCallback near our scheduled time and re-arming as expected.

        2020-08-06T09:36:41.322-07:00 [INFO] "From CreateRecurringTimer: creating timer" "via_callback" "recurring_timer::1"
        2020-08-06T09:36:41.321-07:00 [INFO] "From RecurringTimerCallback: timer fired" {"id":"recurring_timer::1","mode":"via_callback"}
        2020-08-06T09:36:06.319-07:00 [INFO] "From CreateRecurringTimer: creating timer" "via_callback" "recurring_timer::1"
        2020-08-06T09:36:06.318-07:00 [INFO] "From RecurringTimerCallback: timer fired" {"id":"recurring_timer::1","mode":"via_callback"}
        2020-08-06T09:35:31.314-07:00 [INFO] "From CreateRecurringTimer: creating timer" "via_callback" "recurring_timer::1"
        2020-08-06T09:35:31.313-07:00 [INFO] "From RecurringTimerCallback: timer fired" {"id":"recurring_timer::1","mode":"via_callback"}
        2020-08-06T09:34:56.315-07:00 [INFO] "From CreateRecurringTimer: creating timer" "via_callback" "recurring_timer::1"
        2020-08-06T09:34:56.314-07:00 [INFO] "From RecurringTimerCallback: timer fired" {"id":"recurring_timer::1","mode":"via_onupdate"}
        2020-08-06T09:34:24.073-07:00 [INFO] "From CreateRecurringTimer: creating timer" "via_onupdate" "recurring_timer::1"
        2020-08-06T09:34:24.073-07:00 [INFO] "From OnUpdate: create/overwrite doc.active" true "recurring_timer::1"
        2020-08-06T09:05:52.749-07:00 [INFO] "From OnUpdate: no active Timer to cancel, doc.active" false "recurring_timer::1"
        recurring timer 04 log active2
    4. Close the Function Log dialog again. Then, to check the results of the callback, access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the new output status document cur_recurring_timer::1 (note the last_update field is in UTC) and you will see the data written by the Timer’s callback:

        {
          "last_update": "2020-08-06T16:42:01.329Z"
        }
      • Click Cancel to close the editor.

    5. Wait about 30 seconds and repeat the above. The emulated "work" of this Eventing function is merely writing a time stamp to the cur_recurring_timer::1 document about every 30 seconds.

    Test 2: Cancel the Recurring Timer

    1. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document recurring_timer::1 — it should look like this:

        {
          "type": "recurring_timer",
          "id": 1,
          "active": true
        }

        Change "a_number" to 2 to create a mutation, then click Save. The control document is now:

        {
          "type": "recurring_timer",
          "id": 1,
          "active": false
        }
    2. Access the Couchbase Web Console > Eventing page and if necessary select the Function recurring_timer, then click the "Log" link for the Deployed Function to view the activity.

      • Here we see from the Application log that we canceled the sequence — the recurring timer has stopped.

        2020-08-06T09:44:01.333-07:00 [INFO] "From OnUpdate: canceled active Timer, doc.active" false "recurring_timer::1"

    Cleanup:

    To clean up, go to the Eventing portion of the UI and undeploy the Function recurring_timer. This will remove the 2048 documents for each function from the 'metadata' bucket (in the Bucket view of the UI). Remember you may only delete the 'metadata' bucket if there are no deployed Eventing functions.