3 Answers
3

@Ingo has provided a good and correct answer. This answer is provided to augment Ingo's answer & provide details that may be helpful to your understanding.

Know that cron is useful, but to use it effectively, you should understand its limitations.

1. cron has no knowledge of the state of your system during the boot process.

This means that it is your responsibility to ensure that the services required to execute your @reboot entry in your crontab file are available before your script/program is started. In general, this can often be accomplished by simply adding a sleep statement to your @reboot entry in crontab.

2. cron runs under a different environment than your user id.

When you are logged in under a user id (pi for example), the OS has created an environment that includes (among other things) a default path in which to find executables. However, when your cron job executes, it is NOT executed with all of the same environment variables as your user id. Since cron's PATH environment variable is not defined same as your user id, then you should use a "complete" file specification (path) for your executable to ensure your system knows which file(s) you intend to execute or use.

If you want to explore this business of the environment in more detail:

3. a failed cron job needs your help to tell you if or why it fails to execute.

This is related to the limitation above; i.e. your cron job is not actually run under your user id. Linux utilizes three (3) "streams" to communicate with a user: stdin, stderr and stdout. When you use a terminal to interact with your RPi, the system knows where to direct your input/commands at the terminal (stdin to a process), and it also knows to direct any output (stderr and stdout) from that process to your terminal. HOWEVER, unless you tell the system, it doesn't know where to direct the cron user's output or error messages. Thus, when a cron job fails to run, an error message is (may be) generated, but the system doesn't know where this "stream" should be directed, and you (your user id) doesn't have the benefit of this feedback. It's a bit like driving with your eyes closed. Recovering the stderr output from cron is accomplished with a simple "redirect" to a file.

OVERCOMING cron's LIMITATIONS

Fortunately, it's fairly straightforward to deal with all three of these limitations. I'll use your cron job to illustrate how you might deal with all these limitations by modifying your one line cron job:

You tagged the question with python-3 but you call everywhere python that is calling python 2. Because you don't tell us how do you start the script after login it is unclear why it then unexpected runs. You should also use full path calls in crontab:

In addition to what @ingo has stated, crontab can often start running your script before the Pi is able to do any networking, so it might be worth adding a sleep function to your code after your imports.