Timer for switch

hi guys, does anyone know how to code a timer into a switch, say once the switch is activated keep it on for 20 seconds than shut it off?
so far i have

class power_input extends InputPort
{
name = "OPEN"
type = “number”

function set(value)
{

    // update the display
    server.show("OPEN!");                
        
    // set the power pin to whatever was passed in above, on or off
    hardware.pin8.write(1);

}

}

i want to be able to set pin 8 to value of 0 after 20 seconds.

Adding a function with wakeup causes the function to trigger each 20 seconds …

function watchdog() {
imp.wakeup(20,watchdog);
hardware.pin8.write(1);
// or call another function if you want … myFunction();
}

// start watchdog write every 20 seconds
watchdog();

To set pin 8 to 0 after 20 seconds, you can just do this:

imp.wakeup(20, function() { hardware.pin8.write(0); } );

…this runs the inline function 20 seconds later. Right now you can’t cancel wakeups but that’s on the way…

these seem to be timers i just need a time off. i cant have it come back on . just shit it off after 20 seconds and stay off.

That code will make it turn off after 20 seconds, then not do anything else. It won’t come back on unless you call hardware.pin8.write(1) at some point.

you have HTTP In input to turn the light on, but how can you turn it off after a specified time interval WITHOUT using wakeup?

You have to use imp.wakeup. That’s how you do timed events on an imp.

+1 for wanting to be able to cancel imp.wakeups.

The most common pattern that needs these is an inactivity timer. You want to put the imp either from powersave(false) to powersave(true) or even into sleep or deepsleep after (for sake of example) 12 seconds of no event.

Currently I use imp.wakeup(12, checkActivity)
checkActivity() checks a global variable ‘wasActive’. Any activity sets wasActive true. checkActivity() checks ‘wasActive’ at the beginning and always sets it to false before returning.

This results in the imp going to a lower powerstate after anywhere from 12-24 of seconds of inactivity. With the ability to retain a handle to a timer and cancel it, this could be change to a predictable exactly 12 seconds of inactivity. Ideally in addition to the option of cancelling, I could also choose to reset the timer toits original value or to a new value.

P.S. It would also eliminate the need for the global wasActive variable. Any activity would just restart (or cancel then create new) the timer instead of indirectly setting wasActive = true

Canceling wakeups is now implemented, but is in the release after release 23. imp.wakeup() returns a handle that you can use to cancel a wakeup as necessary.