How to Set up Python Scripts with Crontab
Note: This method is applicable to all EG Series/RobustOS Pro devices
Author: Eldar Mustafin
1. Creating a Python Script
First, create your Python script with proper logging and error handling. Here's a template:
import logging
from datetime import datetime
import sys
from pathlib import Path
log_dir = Path('/path/to/your/logs')
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / 'script.log'
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
]
)
def main():
try:
logging.info("Script started")
current_time = datetime.now()
logging.info(f"Current time: {current_time}")
logging.info("Script completed successfully")
except Exception as e:
logging.error(f"An error occurred: {str(e)}", exc_info=True)
sys.exit(1)
if __name__ == "__main__":
main()
2. Making the Script Executable
Save your script (e.g., as task.py)
Make it executable:
chmod +x /path/to/your/task.py
3. Testing the Script
Before setting up crontab, test your script:
/path/to/your/task.py
4. Setting up Crontab
Basic Crontab Syntax
* * * * * command
│ │ │ │ │
│ │ │ │ └─── day of week (0-6) (0 is Sunday)
│ │ │ └────── month (1-12)
│ │ └───────── day of month (1-31)
│ └──────────── hour (0-23)
└─────────────── minute (0-59)
Common Crontab Examples
* * * * * /path/to/your/task.py
0 * * * * /path/to/your/task.py
30 2 * * * /path/to/your/task.py
0 9 * * 1 /path/to/your/task.py
0 0 1 * * /path/to/your/task.py
Setting Up Your Crontab
1. Open crontab editor:
crontab -e
2. Add your script (example):
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PYTHONPATH=/path/to/python/packages
0 3 * * * /path/to/your/task.py >> /path/to/your/logs/cron.log 2>&1
5. Best Practices
- Use Absolute Paths: Always use full paths in your crontab entries
- Set Environment Variables: Include necessary environment variables in crontab
- Redirect Output: Capture both stdout and stderr in logs
- Test Thoroughly: Test your script manually before adding to crontab
- Monitor Logs: Regularly check your log files
- Use Lock Files: Prevent multiple instances from running simultaneously:
import fcntl
import sys
from pathlib import Path
def obtain_lock():
lock_file = Path("/tmp/my_script.lock")
lock_fd = open(lock_file, 'w')
try:
fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return lock_fd
except IOError:
logging.warning("Another instance is running")
sys.exit(0)
lock_fd = obtain_lock()
6. Troubleshooting
- Check Logs: Review both script and cron logs
- Test Permissions: Ensure script has proper execute permissions
- Verify Paths: Confirm all paths are absolute and correct
- Check Environment: Verify environment variables are set correctly
- Monitor Resource Usage: Check CPU and memory usage
7. Viewing Crontab Status
crontab -l
sudo systemctl status cron
sudo grep CRON /var/log/syslog
Related Articles
How to Integrate RCMS API with Python
Project Setup 1. Create project directory: mkdir rcms_api cd rcms_api 2. Install required dependencies with pip for e.x.: python -m pip install requests 3. Create main client file rcms_client.py: import hashlib import hmac import json import time ...
How to Set up Bidirectional SMS Integration with Telegram
This guide describes how to set up bidirectional SMS integration with Telegram on a RobustOS Pro device. After setup, you'll be able to: Receive device SMS messages in your Telegram chat Send SMS from Telegram using simple commands Prerequisites ...
How to Set NTP via Command Line
Understanding the Configuration Structure First, it's helpful to understand how to access the complete configuration structure: 1. You can download the XML configuration from: Web UI → System → Profile → XML Configuration File → Generate → Download ...
How to Set up RS422 Serial Connection
1. Physical Connection Setup Hardware Requirements MOXA Uport 1150 device Serial cable RobustOS PRO device with RS422 interface Pinout Connections Connect the following pins between your devices: T+ → RX1+ T- → RX1- R+ (D+) → TX1+ R- (D-) → TX1- GND ...
How to Set up Ping Detection
Why Ping Detection is Critical Ping detection serves as an essential keep-alive mechanism for your RCMS (Remote Cloud Monitoring Solution) connectivity. This feature: Actively monitors real-time connectivity to the RCMS platform Identifies network ...