Skip to main content

Schedule the job: one crontab line that runs the crawl daily

Put the course's crawl script on a daily cron schedule, append everything it prints and its exit code to runs/cron.txt, and read the file the next morning.

From our run on
  1. this run: 20 rows in runs/quotes-2026-11-21T051920Z.csv
  2. latest.csv before: 20 rows, after: 20 rows
  3. ok
Lesson 13 of 20 10 min read

To schedule a web scraper on Linux or macOS, add one line to your crontab that gives a time, moves into the script's folder and starts the script, with its output appended to a file. Cron then starts the crawl every day whether you are at the keyboard or not, and the file keeps what each run printed and how it exited.

What you build here is a crontab entry that starts stop_bad_run.py at 06:15 every morning, and a runs/cron.txt that gains a few lines and an exit= line from every run, including the runs you slept through.

Every run so far was typed

Lesson 12 ended with a script that crawls up to 20 pages, writes them to a dated CSV file, and replaces runs/latest.csv only when the run looks whole. It exits 0 when it replaced the file, 1 when the key is missing or nothing came back, and 2 when it held the run. Every one of those runs started because you typed the command.

This lesson adds no lines to the script. The new line goes in your crontab. What cron starts is your own edited copy of lesson 12's script, not the recorded one printed below, so check it first. Its params line must send your user_agent and a delay of 1000:

    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
              "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}

Run grep -n user_agent stop_bad_run.py in your course folder. You should see that second line with your own bot name and contact address. If grep prints nothing, make the change before you schedule anything, because from here on nobody reads what the script sends.

This clip reads the crontab line.

Schedule the crawl with cron. 51 s, no sound. The words are on screen, and the captions button shows them at your own text size.
Read the transcript

Schedule the crawl with cron. One crontab line: when to run, what to keep, and where it goes.

The first five fields set the time: 06:15, every day. minute: 15. hour: 6. day of month, month, day of week: * * *. 06:15: every day. 5: fields before the command.

The rest of the line keeps a record of every run. [ -r "$HOME/.spider-key.sh" ]: is the key file there?. echo "exit=$?": the exit code, on its own line. >> runs/cron.txt: adds to the file. 2>&1: errors go to the same file.

Each run adds its printed lines and one exit line to the file. this run: 20 rows in runs/quotes-2026-11-21T051920Z.csv. latest.csv before: 20 rows, after: 20 rows. ok. exit=0, added by the echo. 2: runs on record, each by hand. 2: of them exit 0.

Read the exit line first. It says how the run ended. The last line of a run: tail -n 4 runs/cron.txt. exit 0: latest.csv was replaced. exit 1: Key missing or nothing came back. exit 2: Run held, latest.csv kept. This run: exit 0.

Read the full page. The page is at spider.cloud/learn/course/schedule-the-job.

What a scheduled run has to look like

Before cron takes over, look at what two hand-started runs of the same script leave behind. The script reads its key from the SPIDER_API_KEY environment variable. This is lesson 12's recorded script as it ran under Python 3.14.7. It sends no user_agent and no delay, which is why your copy has the edit above:

"""Crawl a site through the Spider API, save the run, and replace runs/latest.csv only when
the run looks whole.

    python3 stop_bad_run.py URL [--short]

--short lowers the page limit to 5, to show what a cut-off run does.
A run looks whole when every page answered 200 and it has at least 80 percent of the rows
latest.csv has. A run that does not is kept in its own file and logged as held, and
latest.csv stays as it was.
Exit 0: the run replaced latest.csv.
Exit 1: the key is missing or nothing came back.
Exit 2: the run was held.
"""
import csv
import json
import os
import shutil
import sys
import urllib.request
from datetime import datetime, timezone

API = "https://api.spider.cloud/crawl"
LATEST = os.path.join("runs", "latest.csv")
LOG = os.path.join("runs", "log.txt")


def count_rows(path):
    if not os.path.exists(path):
        return 0
    with open(path, newline="", encoding="utf-8") as f:
        return max(sum(1 for _ in csv.reader(f)) - 1, 0)


def main() -> int:
    if len(sys.argv) not in (2, 3) or sys.argv[2:] not in ([], ["--short"]):
        print("usage: python3 stop_bad_run.py URL [--short]")
        return 1
    url = sys.argv[1]
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    os.makedirs("runs", exist_ok=True)
    started = datetime.now(timezone.utc)
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown"}
    if "--short" in sys.argv:
        params["limit"] = 5
    req = urllib.request.Request(API, data=json.dumps(params).encode(), headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=300) as resp:
        pages = json.load(resp)
    if isinstance(pages, dict):
        pages = [pages]
    if not pages:
        print("nothing came back")
        return 1

    rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
                   for p in pages))
    out = os.path.join("runs", started.strftime("quotes-%Y-%m-%dT%H%M%SZ.csv"))
    with open(out, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["url", "status", "bytes"])
        writer.writerows(rows)

    before = count_rows(LATEST)
    whole = all(status == 200 for _, status, _ in rows) and len(rows) >= 0.8 * before
    verdict = "ok" if whole else "held"
    if whole:
        shutil.copyfile(out, LATEST)
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(f"{started:%Y-%m-%dT%H:%M:%SZ}  {url}  pages={len(rows)}  limit={params['limit']}  {verdict}\n")

    print(f"this run: {len(rows)} rows in {out}")
    print(f"latest.csv before: {before} rows, after: {count_rows(LATEST)} rows")
    print(verdict if whole else f"held: {len(rows)} rows is under 80 percent of {before}, latest.csv not replaced")
    return 0 if whole else 2


if __name__ == "__main__":
    sys.exit(main())

Both runs were started by hand, on the command python3 stop_bad_run.py https://quotes.toscrape.com/. The first, on 2026-11-20 at 22:35 UTC, took 2.0 seconds, exited 0, and printed:

this run: 20 rows in runs/quotes-2026-11-20T223514Z.csv
latest.csv before: 0 rows, after: 20 rows
ok

The second, on 2026-11-21 at 05:19 UTC, took 4.8 seconds, exited 0, and printed:

this run: 20 rows in runs/quotes-2026-11-21T051920Z.csv
latest.csv before: 20 rows, after: 20 rows
ok

No scheduler started either one. The records kept only the printed lines and the exit code, not the CSV rows, so they show that each run saved 20 rows and ended ok, and nothing about whether any row changed between the two dates.

Even so, the pair shows what a daily job should leave you: a new file named for its start time in UTC, a count to set beside the last one, and a verdict. Cron gives the job no terminal to print to, so the crontab line has to send those lines to a file.

Write the line

Cron reads a table where, in the words of the crontab(5) manual page, each line means "run this command at this time on this date". The same page lists the time fields in order: minute, hour, day of month, month, day of week. A * in a field matches every value.

Two things your terminal has are missing when cron starts a job. The first is the folder: the script writes to runs/, so the line has to cd there first. The second is the key. The manual page lists what cron sets for a job itself, starting with "SHELL is set to /bin/sh, and LOGNAME and HOME are set from the /etc/passwd line of the crontab´s owner." A variable you exported in a terminal is not on that list.

Keep the key in a file of its own in your home folder, outside the course folder, so it never ends up in a copy or a commit of your scripts. Create the file and lock it to you alone before the key goes in:

touch "$HOME/.spider-key.sh"
chmod 600 "$HOME/.spider-key.sh"

Then open .spider-key.sh in your editor and put in it the same export line for SPIDER_API_KEY that you type before a run by hand.

Next, from inside your course folder, run:

mkdir -p runs
pwd
command -v python3

The mkdir makes runs/ now, because the redirect in the crontab line needs it before Python starts. pwd prints the full path of the course folder, and the crontab line uses that path twice. The last command prints the full path to your Python. Then open your crontab with crontab -e and add this line. Put the path pwd printed where it says /home/you/course, in both places, and your Python's path where it says /usr/bin/python3:

15 6 * * * { cd /home/you/course && [ -r "$HOME/.spider-key.sh" ] && . "$HOME/.spider-key.sh" && /usr/bin/python3 stop_bad_run.py https://quotes.toscrape.com/; echo "exit=$?"; } >> /home/you/course/runs/cron.txt 2>&1

15 6 * * * is 06:15 every day. Everything inside the braces writes to runs/cron.txt, the cd included. The && links mean each step starts only when the one before it worked: the folder change, the check that the key file can be read, loading it, and then the script. echo then writes the last exit code, so the file records it next to the printed lines.

The [ -r ... ] check is there because of how cron's shell treats .. When /bin/sh cannot read the file you hand to ., it can stop the whole line on the spot, and then echo never runs. With the check in front, a missing key file just makes the chain stop, and echo still writes its line.

That means exit= reports whichever step failed last, not only the script. An exit=1 with no this run: line above it comes from the shell: either the cd failed, and its error sits just above, or the key file could not be read, and the line stands alone. An exit=1 after the script's own message, such as set SPIDER_API_KEY first, comes from Python.

The log path is written out in full, so it does not depend on where the job happens to start. If runs/ has been deleted or renamed, the shell cannot open the log at all, and nothing reaches it. That error goes wherever your system sends cron output it was not told where to put, often local mail for your user, as crontab(5) describes under MAILTO. A day with no new lines in runs/cron.txt means you look there first.

The redirect after the closing brace covers every command inside. >> appends, so each run adds to the file and none clears it. 2>&1 sends error output to the same place, so a traceback or a missing key ends up in the file next to the normal lines. The Bash manual says "The order of redirections is significant", and its example of > dirlist 2>&1 "directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist". Put the two the other way round and errors go somewhere you will not look.

End the crontab with a newline after the last line. The manual page says "cron requires that each entry in a crontab end in a newline", and a file without one is treated as broken. Save, then run crontab -l to see the line cron now holds.

Choose the hour with the clock in mind. The same page says cron never runs a job set inside the hour a daylight saving change skips, and times that occur twice "will cause matching jobs to be run twice". Keep the job outside that hour.

Read it the next morning

After a day, tail -n 4 runs/cron.txt shows the newest run: the lines your edited script printed, then exit=0, exit=1 or exit=2. That last line is lesson 12's verdict, kept for you. An exit=2 means a run was held and latest.csv still holds the earlier rows, so open that run's dated file before anything else.

A daily job visits the site every day with nobody checking it. Keep the delay from lesson 4, and read the site's robots.txt and terms again from time to time, as in lesson 3, since cron will not notice when they change. The web scraping guide covers what changes once a crawl runs on a timer and nobody is watching it.

Try it yourself

Prove the line works today instead of waiting for tomorrow. Cron reads the time fields in the machine's local time, but the script names its files in UTC, so look at both clocks and count the log's lines before you start:

date
date -u
wc -l runs/cron.txt

The first command gives the local time to set the job by. Change the first two fields so the job starts three minutes from now. At 14:07 local, for example, write 10 14 * * *. Note what that minute is in UTC from the second command. The third prints how many lines the log has now. If the file is not there yet, that is fine, since cron will create it. Save, wait until the minute passes, then run:

wc -l runs/cron.txt
tail -n 4 runs/cron.txt

You are done when the line count has grown, the last line reads exit=0, and the this run: line above it names a CSV whose time stamp falls in the UTC minute you noted, a file that was not in runs/ before the trial. Then set the fields back to 15 6.

Do this, avoid this

Do this

  • Create runs/ yourself before the first scheduled run, so the log has somewhere to go.
  • Put the cd inside the braces and append with >> and 2>&1, so a failed cd, normal lines, errors and the exit code all reach runs/cron.txt.
  • Try the line with a start time a few minutes away before you set the daily one.

Avoid this

  • Five asterisks in the time fields. That starts the crawl every minute.
  • A single > in place of >>. Each run would empty the file and leave only its own lines.
  • Typing the key itself into the crontab, where crontab -l prints it for anyone at your screen, or keeping the key file inside the course folder.
  • A time inside the hour your clock skips or repeats for daylight saving.

Next

Cron now starts the crawl at 06:15 whether the run before it has finished or not. The two hand-started runs took 2.0 and 4.8 seconds. A crawl of a slower site can take far longer. Lesson 14 makes the script stand aside when it starts and finds the last run still going.

Sources

  1. crontab(5), Linux manual page, man7.org Read
  2. GNU Bash Reference Manual, 3.6 Redirections Read

Run this on a page you care about

The playground sends the request this page describes and shows you the response. Keyless runs work without an account and are rate limited.