Cron定时任务配置咨询:实现开机后仍可每分钟执行的Python脚本定时任务
Hey there! Let's figure out why your cronjob isn't running after a restart and get it fixed properly.
First, let's talk about the issue with your current cron command:
- /usr/bin/python3 -c 'from erpnext_sync import main; main()'
The core problem here is that cron runs in a stripped-down environment—it doesn't use your full user shell setup, and its default working directory is your home folder, not where your erpnext_sync.py script lives. That means Python can't find the erpnext_sync module because it's not in the default module search path.
Here's how to fix this step by step:
1. Update your cron command to target the script directly
Instead of using the -c flag to import the function, switch to running the full script after navigating to its directory. This ensures Python can locate all necessary files and modules without path issues:
* * * * * cd /home/user_name/frappe-bench/biometric-attendance-sync-tool && /usr/bin/python3 erpnext_sync.py
This command first changes to the script's directory, then runs the script—this eliminates any import errors caused by incorrect working directories.
2. Ensure the cron service starts automatically on boot
On Ubuntu, cron usually starts on boot by default, but it's worth double-checking and enabling it if needed:
- Check the current status of the cron service:
sudo systemctl status cron - If it's not set to start automatically, run this to enable it:
sudo systemctl enable cron
This guarantees that when you restart your PC, the cron service launches right away, and your scheduled tasks start running immediately.
3. Add logging to debug future issues
If you ever run into problems again, capturing the cron job's output can help you diagnose what's wrong. Modify the command like this to log both standard output and errors:
* * * * * cd /home/user_name/frappe-bench/biometric-attendance-sync-tool && /usr/bin/python3 erpnext_sync.py >> /var/log/erpnext_sync_cron.log 2>&1
You can view the log later with cat /var/log/erpnext_sync_cron.log to see exactly what's happening if the job fails.
Once you edit your crontab (using crontab -e), save the corrected command, and confirm cron is enabled on boot, your job should run every minute—even after restarting your computer.
备注:内容来源于stack exchange,提问作者fit




