Automation pause and restart and run for remaining time

I have Home Assistant configured to turn on 2 submersible motors.

Motor 1 configured to run for 2 hours and turn off by Automation
Motor 2 configured to run for 45 min and turn off by Automation

Its working very fine, if there is no power cut.
The problem is the grid power goes off very often for few min and comes back.
My home assistant machine is running on UPS.
When power goes off Home assistant doesn’t know and automation is still running.

I would like to add a sensor ( mostly a door sensor connect with a relay) to detect the power failure and stop the automation, restart it when the power comes back only for remaining time.

I am asking experts out here, how do I restart the automation with the remaining time?
I am not a programmer, but I will manage if some one explains.

One way to do that is by using a Timer with an enabled restore option.

Post the automations you are currently using to control the motors.

Hi, Not sure if this will help, but we have lots of load shedding in South Africa. One of local suppliers have developed a load shedding detector, which essentially an Tuya garage opener and added a couple of relay with wifi output. The loadshedding detector will tell you when mains is available or not and you can use it to trigger an automation or ignore (set in conditions)

This the product and you can build yourslef if you can buy a garage opener in your country