Using Macrodroid:
- On the Triggers tab, under Battery/Power section select "Power Connected/Disconnected", then choose "Power Disconnected".
- On the Actions tab, under Macrodroid Specific, select "Wait Before Next Action", then set the delay period to 20 seconds.
- On the Actions tab, under Device Actions, select Reboot/PowerOff, then choose "Power Off". If "Power Off" does not work on your device, choose "Power Off (Alternative)".
- Save the macro and give it a name.
When completed, the macro will look like the image below. Use the 3-dot to test the macro.
Note: Powering off requires the device be rooted.
Update:
The way the macro is programmed above does not allow to stop the device from being power off if the charger is connected again before the 20 seconds delay expires. To stop the trigger, a condition to check the state of the device after the delay expires but before the action to power it off.
Edit the macro. Add a new action. Under the Actions, on the Conditions/Loops section, select "If clause". Add a condition. Select "Power Connected" under the Battery/Power section and choose "Power Disconnected", then OK. Click the up and down arrows button on the Actions box, move the "Power Off" action inside the "If...End If". Save the macro. The macro will look like the image below.