In the code above, the Defrag function contains a local, static, time_t variable which stores the last time this function was called.
The first time the function is called, the static time_t variable (LastDefrag) is created and set to zero. That variable is subsequently set to the system time if a condition is met: namely that the elapsed time period since the last call of Defrag is greater than one hour.
When the main function calls Defrag again, it ignores the creation and initialisation of the static time_t variable. It simply makes the comparison for time passed, and (given we’ve only waited a couple of seconds between calls) the condition is not met and defragmentation is not commenced.
You can verify that this variable is working correctly by changing the function to test for a difference of greater than 1 second (instead of 1 hour, which is the 3600 seconds you see in the code).
When you make this change, the Defrag command will run twice because the time difference is greater than stipulated.
And that’s all there is to it. Function level static variables are definitely the nicest of them all.