The code on the page should work fine without that -- let me try to explain it in a different way, and see if it's clearer (if it is, we can update the help page :-)
Let's say you have a module called my_module
, which contains a function called my_long_running_process
. What you want is for the function my_long_running_process
to be kept running. If it exits -- either due to the 6-hour task run limit, or a server reboot (hopefully rare), or even if it crashes -- you want it to be started up as soon as possible.
If you put the code that's on the Long running tasks page into a separate script, let's call it long_running.py
, and run it, what it will do is try to acquire a lock. If the lock is already held by another process on the same machine, then it will exit immediately. If the lock is not held by another process, it will run your my_long_running_process
function, and then exit when that function completes. The lock will be automatically released if the long_running.py
script exits for any reason -- whether it's due to the process being killed, a server reboot, or a crash.
Now, all scheduled tasks -- not processes run in consoles -- on PythonAnywhere for a particular user account are currently run on the same machine. (This might change in the future, but not before we have a better solution for long-running tasks.)
What that means is that if you set up the script python3.6 long_running.py
as a scheduled task -- scheduled every five minutes by setting up 12 hourly tasks that just run it -- then the first time it was run, it would try to acquire the lock, and succeed, so it would run your my_long_running_process
function. The next time it was run, five minutes later, it would try to acquire the lock, but it would see that another process already has it, so it would immediately exit. The next time, the same thing. The lock would stop any extra copies of the process from running.
Now, after 6 hours, the process that had the lock would be killed. (Or perhaps before then, if the server was rebooted -- again, unlikely -- or the script crashed.) The lock would automatically be released. And within a maximum of five minutes, the hourly task would kick off again. This time it would find that no other process had the lock, so it would acquire it, and would start running the code.
The net effect would therefore be that the function my_long_running_process
would be kept running forever, with a maximum outage time of five minutes.
Is that any clearer?