We all have to deal with repetitive tasks everyday, and this can be draining on our minds. What if we could automate those boring tasks, so that we could focus on the tasks that matter? Well, there is a tool for that.
Task automation is the process of using software to perform repetitive or time-consuming tasks without manual intervention. Whether it’s backing up files, sending email reports, or capturing images from a camera, automation saves time, reduces errors, and lets you focus on more important work. With just a few lines of code and the right scheduling tool, you can set up systems that run reliably day after day, hour after hour, all on their own.
Imagine you have a security camera (or any IP camera) that streams video over your network for monitoring purposes. You want your computer to automatically take one snapshot from that camera every hour and save it as an image file.
There are two popular ways to do this in Python:
-
Option 1: Use a tool called
cron(a built-in scheduler in Linux). -
Option 2: Use a Python library called
scheduleto run your code inside a long-running script.
Both can work, but one is usually better for this kind of task. Let’s break it down in simple terms.
What Are We Trying to Do?
- Connect to a camera using its RTSP address (like a web link for video streams).
- Grab one single image.
- Save it with a timestamp (e.g., image_20260112_140000.jpg).
- Do this once every hour, automatically, without you having to press a button.
Shouldn't be that hard, but how you schedule it matters!
Option 1: Use Cron (The System Timer)
Cron is a built-in feature in Linux (and macOS) that can run any command or script at specific times, just like scheduling an alarm, but for your computer. Technically, a cron job is a scheduled task executed automatically by the cron daemon (crond) on Unix-like operating systems (such as Ubuntu/Linux). It allows users to automate the execution of scripts, commands, or programs at predefined times or intervals, based on a configuration known as a crontab (short for cron table).
How It Works
Let's look the syntax for creating a cronjob:
┌───────────── minute (0–59)
│ ┌──────────── hour (0–23)
│ │ ┌──────────── day of month (1–31)
│ │ │ ┌──────────── month (1–12)
│ │ │ │ ┌──────────── day of week (0–6, where 0 = Sunday)
│ │ │ │ │
* * * * * command_to_execute
To create a cronjob, this time specification is combined with a script (python, shell, etc.) for timely execution.
For our use-case, we will:
- Write a short Python script that does one thing: connect to the camera, take a picture, and save it.
- Tell cron: “Run this script every hour.”
The computer handles the rest, even if you’re not logged in.
import cv2
import os
from datetime import datetime
# Your camera's RTSP link
rtsp_url = "rtsp://username:password@192.168.1.65:554/stream"
# Folder to save images
folder = "hourly_photos"
os.makedirs(folder, exist_ok=True)
# Connect and grab one frame
cap = cv2.VideoCapture(rtsp_url)
success, frame = cap.read()
cap.release() # Close the connection right away
if success:
filename = f"{folder}/photo_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
cv2.imwrite(filename, frame)
print("Photo saved:", filename)
else:
print("Failed to get image from camera")
Setting Up Cron
Open the terminal and type:
crontab -e
Then add this line to automatically invoke the script at every hour:
0 * * * * /usr/bin/python3 /home/<username>/<script_name>.py >> /home/you/photo_log.txt 2>&1
That’s it! The computer will now take a photo every hour.
Why Should It Matter?
- Simple: One script, one job.
- Reliable: If the script crashes one time, cron will still try again next hour.
- Lightweight: Uses no memory when it’s not running.
- Easy to test: Just run
python3 script_name.pyin the terminal to see if it works.
Option 2: Use Python’s schedule Library
This method keeps a Python program running all the time. Inside that program, you tell it: “Every hour, run this function.”
import schedule
import time
import cv2
from datetime import datetime
def take_photo():
cap = cv2.VideoCapture("rtsp://...")
success, frame = cap.read()
cap.release()
if success:
cv2.imwrite(f"photo_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg", frame)
# Schedule the job
schedule.every().hour.do(take_photo)
# Keep the program running forever
while True:
schedule.run_pending()
time.sleep(60)
Why This Can Be Tricky
- The script must stay running 24/7. If your computer restarts or the script crashes, it stops working, unless you add extra tools to restart it.
- It uses a little bit of memory and CPU even when doing nothing.
- Debugging is harder: if something goes wrong at 3 AM, you might not know unless you set up logging.
- For a task that only runs once an hour, keeping a program alive the whole time is like leaving your car engine running all day just to drive one minute every hour!
So… Which Should You Choose?
| Situation | Best Choice |
|---|---|
| You want to take one photo per hour (or per day) | Cron |
| You need to take many photos per minute | Consider schedule (to avoid opening/closing the camera too often) |
| Your task is simple and doesn’t depend on past runs | Cron |
| You’re new to automation and want something easy to set up and forget | Cron |
In essence, a Rule of Thumb can be established:
If your task happens less than once per minute and doesn’t need to remember anything from last time, use cron.
Final Advice
For taking hourly snapshots from a camera, cron is simpler, more reliable, and easier to manage, especially if you’re just getting started.
Save the schedule library for more complex projects where your program needs to stay awake, react in real time, or remember things between actions.
Remember, Start simple, and Automate wisely.
Happy automating!!
Top comments (0)