Reschedule CC task before timeout

Hi

I want to reschedule my CC task before it reaches the timeout. Is there a nice way to do this?

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)
}

Is the while(true) loop here not missing a break out of the loop in the case where it is not timing out?

E.g.

let isComplete = false;
while (true) {
    if (timingOut) {
        ...
        break;
    }
    if (isComplete) {
        break;
    }

    // do lots of work
    ...

    isComplete = true;
}

@benita Yes, and no.

If this was an actual loop then yes (but then we would probably never actually use a while (true) loop but rather a while (someCondition === true))

In this case however the while (true) statement is basically just pseudocode to demonstrate how the timeout handler works.