CloudCode Task Timeout

I’m running a task that is loading data from another database JA DB and it’s timing out. How can I keep the task from restarting?

You can add the following to your task to catch timeouts and high memory usage.

export async function run(event) {

    this.on('beforeTimeout', () => {
        // The task is about to timeout, just return.
        // You can also report errors to log services
        return;
    });
    this.on('highMemory', () => {
        // The task is reaching the memory threshold, just return.
        // You can also report errors to log services
        return;
    });

}

If the beforeTimeout or highMemory events trigger, one should consider changing the task or enqueue another task to continue.

1 Like

Hi @mike_barnes. I am trying to test if this works, but I am not able to trigger the beforeTimeout function using a while loop. My CloudCode task is version 1.11.0

export async function run() {
    this.on('beforeTimeout', () => {
        const _timeout_error = `${this.name} - Script timeout imminent!`;
        console.log(_timeout_error);
        return;
    });

   while (true) {
    }

}

I still automatically retries the task. My goal is to prevent the automatic retry.

14:26:54.491 [QUEUE:INFO] Moved from state ‘QUEUED’ to ‘STARTED’

14:31:55.482 [QUEUE:ERROR] Moved from state ‘STARTED’ to ‘ERRORED’: ‘{“errorMessage”:“2021-06-24T12:31:55.367Z 3602ad75-e520-4044-9d87-8b65c82bbb46 Task timed out after 300.00 seconds”}’

14:31:56.496 [QUEUE:INFO] Moved from state ‘ERRORED’ to ‘STARTED’

14:36:56.816 [QUEUE:ERROR] Moved from state ‘STARTED’ to ‘ERRORED’: ‘{“errorMessage”:“2021-06-24T12:36:56.606Z 33f77be2-a8a2-4501-992e-ecec7a842c14 Task timed out after 300.08 seconds”}’

14:37:01.846 [QUEUE:INFO] Moved from state ‘ERRORED’ to ‘STARTED’

14:42:02.100 [QUEUE:ERROR] Moved from state ‘STARTED’ to ‘ERRORED’: ‘{“errorMessage”:“2021-06-24T12:42:01.987Z 0e5e10d6-4b13-44c6-a3d7-c3dab27d5e3d Task timed out after 300.10 seconds”}’

14:42:32.107 [QUEUE:INFO] Moved from state ‘ERRORED’ to ‘STARTED’

14:47:33.021 [QUEUE:ERROR] Moved from state ‘STARTED’ to ‘ERRORED’: ‘{“errorMessage”:“2021-06-24T12:47:32.891Z 70bb20f2-ef27-48d1-a0b9-ba8cc942baac Task timed out after 300.09 seconds”}’

14:48:33.035 [QUEUE:INFO] Moved from state ‘ERRORED’ to ‘STARTED’

1 Like

@david - Adding a timeout to your while loop with something like this should work, waiting for 50ms in each iteration:

while(true) {
    await new Promise(resolve => setTimeout(resolve, 50));
}

If you have asynchronous operations in the while loop, then the beforeTimeout function should be triggered without requiring the above timeout.

1 Like

I believe this is a more complete example