Yes, here is a basic pattern for doing just that
export async function run() {
// start our timeout mechanism as false
let timingOut = false;
// in the timeoutCallback we set the mechanism to true
this.on('beforeTimeout', () => {
console.log("in beforeTimeout: Marking timingOut: true")
timingOut = true;
});
// manual timeOut incase I want lots of time to finish off what the task is busy with before rescheduling
let myTimeout = setTimeout(function () {
console.log("in setTimeout: Marking timingOut: true")
timingOut = true;
}, 4 * 60 * 1000)
// here is a loop that is doing a lot of work that will maybe cause the task to run out of time
while (true) {
// the first thing I check in my loop is if the timeout mechanism is true
if (timingOut) {
// mechanism is true so now I need finish up my work and reschedule
// finishing the work
let user = await DB.user.first();
await user.save();
// rescheduling the task
await CloudCode.scheduleTask({ task: this.name, parameters: { } });
console.log('Task rescheduled')
// breaking the loop
break;
}
console.log('Doing lots of work');
// this promise just allows my while loop to trigger the beforeTimeout
// THIS IS JUST A SIMULATION OF WORK
// REMOVE IN YOUR IMPLEMENTATION
await new Promise(resolve => setTimeout(resolve, 1000));
}
// if we reach the end of the work before the timeout we need to clear the timeout
clearTimeout(myTimeout)
}