Set 30 second interrupt timer from callback function

I have an IoT use case. An ESP8266 is subscribed to an MQTT topic waiting for actions. A payload is published via MQTT, causing a callback function to raise a relay pin to high. I need to set a non-blocking timer which returns the pin to low after 30 seconds.

It seems that using the hardware timer1 is the right way to do this, but the examples I have found usually blink an LED continuously using attachInterruptInterval().

Because this is happening in the callback function, I don't have control from the loop to turn the relay off.

I'm having trouble wrapping my head around how to do this properly, and can't find an example for my use case.

Does anyone have any advise on if this is possible and if so how?


If you define variable as following

volatile boolean CallbackSwitchedOnFlag = false;
boolean RelaisIsOn = false;
unsigned long SwitchedOnMillis = 0;

and set CallbackSwitchedOnFlag in your Callback-function true
you can check in your mainloop

if ( !RelaisIsOn && CallbackSwitchedOnFlag ) {
  SwitchedOnMillis = millis();
  CallbackSwitchedOnFlag = false;
  RelaisIsOn = true;  

if (RelaisIsOn) {
  if (millis() - SwitchedOnMillis >= 30000) {
      //Your code to switch off the relais
      RelaisIsOn = false;

The main concept is to have flag-variables set to true
if true that initiate something and immetiately after initiating set the flag-variable false again
to ensure that only one initiation is done (the snapshot if millis()
only after your timing is over reset RealisIsOn to false to set the logic ready for a new start

best regards Stefan