I would like to be able to run some code when the worker script is shutting down, and the data stored in the global JavaScript variables are about to be cleared. This would allow me to store information in global JavaScript variables that would persist between worker requests, and before shutdown sends that information to an external API for logging.
For my purposes, this would be useful for creating custom analytics beyond what Cloudflare provides in the dashboard.
Awesome! This is a common use case of event.waitUntil and asynchronous requests. Workers doesn’t generally support an ‘unload’ hook, although we have not ruled it out. In general though, Workers are restarted so infrequently that customers find they only ‘lose’ the tiniest fraction of data. For sites which get a moderate amount of traffic, your Worker will most likely only be restarted a single time per week, making the data very accurate even given the negligible losses.
You could alternatively provide a method to push those data periodically (Once a day? Once per hour?). That could also run before restart. It could be counted as a request, per billing purposes.
I didn’t realize that the Worker scripts would persist for so long. That should work for my use-case.
I suppose this function could still be useful if someone were making frequent updates to their Worker script. Then the script could have a chance to do any necessary shutdown operations before it started the new version.
But, you mention that this is a common use case for event.waitUntil. Can we safely use a setTimeout inside event.waitUntil to accomplish a delayed callback? Like this worker (which performs a task when the worker has been idle for Xms)?
(the demo is simple, not efficient. With a little bit more code, it is possible to avoid calling a new setTimeout for each request.)
But, my question is: Can we trust .waitUntil completely? Do the worker run-time guarantee that the worker will not be terminated (which will wipe clean data in the worker’s memory) while waitUntil is not resolved? Even when that resolution waits on a setTimeout? Or, do the worker run-time only guarantee that for a limited time, say 5min, 1 week, 30ms, or not at all/0ms after response has been returned?