If the idea is to ensure that a catastrophic miner exodus doesn't happen, the "difference" you're calculating should only care about downward differences. Upward differences indicate more mining activity and so shouldn't cause a halving skip.
But I don't think any scheme like this that only acts on the basis of difficulty will be sufficient. If it gets to the point where a sudden drop in mining difficulty happens, it is very likely that simply delaying the next halving or even ending halving all together will not be sufficient to correct for whatever is causing hashrate to tank. There is also the danger of simple difficulty stagnation, which this mechanism wouldn't detect.
The relationship between difficulty and security becomes less and less predictable the longer you want to look ahead. There's no long term relation between difficulty and any reasonable security target. A security target might be something like "no colluding group with less than $1 trillion dollars at their disposal could successfully 51% attack the network (with a probability of blah blah)". There is no way to today program in any code that detects based on difficult alone when that criteria is violated. You would have to program in assumptions about the cost of hashrate projected into the future.
I can't think of any robust automatic way to do this. I think to a certain degree, it will have to be a change that happens in a fork of some kind (soft or hard) periodically (every 10 years? 30 years?). The basic relations needed is really the cost in Bitcoin of the security target (ie the minimum number of Bitcoin it should take to 51% attack the system) and the cost in Bitcoin of acquiring a unit of hashrate. This could be simply input into the code, or could use some complicated oracle system. But with that relation, the system could be programmed to calculate the difficulty necessary to keep the system secure.
Once that is in place, the system could automatically adjust the subsidy up or down to attract more or less miners, or it could adjust the block size up or down to change the fee market such that more or less total fees are collected each block to attract more or less miners.