# One run at a time: lock the job so a second start exits | Spider

Hold an exclusive lock on runs/job.lock so a second start of the crawl script sends no request and exits 3 while the first run is still fetching.

Canonical: https://spider.cloud/learn/course/one-run-at-a-time/

To keep two copies of a job from running at once, have the script take an exclusive lock on a file before it sends anything, and exit straight away when another process already holds it. The operating system grants that lock to one process at a time and drops it when the process ends, so a second start finds the first still working and stops.

When you finish this lesson you will have `one_at_a_time.py`, a lock file at `runs/job.lock` that names the run holding it, and an exit code of 3 that you saw for yourself in a second terminal.

## Nothing stops a second copy

[Lesson 12](/learn/course/stop-on-a-bad-run/) left you with `stop_bad_run.py`. It crawls up to 20 pages, writes them to a dated CSV file, copies that file over `runs/latest.csv` only when the run looks whole, and adds a line to `runs/log.txt`, the log from [lesson 11](/learn/course/write-a-run-log/).

Nothing in it knows whether another copy is already running. A scheduler starts the job at the time you gave it, finished or not, and you might start one by hand while the scheduled one is fetching. Two copies then crawl the same site at the same time. Each writes its own dated file, and the copy that finishes second compares itself with whatever the first just put in `latest.csv`. Any [web scraping](/web-scraping/) job left to run unattended meets this sooner or later, usually on the day the site is slow.

## The lock

Python reaches the lock through `fcntl.flock`. The Linux manual for the call it wraps describes it as "apply or remove an advisory lock on an open file", and for the exclusive kind it says "Only one process may hold an exclusive lock for a given file at a given time."

On its own, a second `flock` call waits in line until the first process lets go. That is the wrong behavior for a scheduled job, since the late copy would start crawling the moment the early one finished. The same manual page gives the way out: "To make a nonblocking request, include LOCK_NB (by ORing) with any of the above operations." With that flag the call fails at once, and the manual names the error `EWOULDBLOCK`, for when "The file is locked and the LOCK_NB flag was selected." Python's documentation for `fcntl.flock` says that "If the flock() call fails, an OSError exception is raised." The script catches it and stops.

The release needs no code. The manual says the lock is released "when all such file descriptors have been closed", and a process that exits closes its files, crashes included. So the test is whether the lock is held, not whether the file exists. A leftover `job.lock` from last night does nothing to tonight's run.

## What one_at_a_time.py adds

Compared with lesson 12's recorded script, these lines are new or changed:

- `import fcntl` and a `LOCK` constant for `runs/job.lock`.
- Right after `os.makedirs`, the script opens the lock file with `"a+"` and asks for `LOCK_EX | LOCK_NB`. When the lock is taken, it reads the file, prints the line it finds there, prints `no request sent` and returns 3.
- Once it holds the lock, it empties the file and writes its own start time and process id into it.
- The `--short` option is gone, and the script now prints its log line instead of the three summary lines.

The `"a+"` mode matters. Opening with `"w"` would empty the file before the lock check, wiping the line a refused start is meant to read. `"a+"` leaves the content alone, and only the process that wins the lock clears it.

The script reads your key from the `SPIDER_API_KEY` environment variable. Here it is as it ran on 2026-11-20 under Python 3.14.7, twice, the second start one second after the first:

```python
"""Crawl a site through the Spider API, save the run, and replace runs/latest.csv only when
the run looks whole. Only one copy of the job runs at a time.

    python3 one_at_a_time.py URL

The job holds a lock on runs/job.lock while it works. A second start that finds the lock
taken sends no request, prints who holds it, and exits 3. The system frees the lock when
the first job ends, even if it crashes.
Exit 0: the run replaced latest.csv.
Exit 1: the key is missing or nothing came back.
Exit 2: the run was held, as in lesson 12.
Exit 3: another run is still going.
"""
import csv
import fcntl
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")
LOCK = os.path.join("runs", "job.lock")


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) != 2:
        print("usage: python3 one_at_a_time.py URL")
        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)
    lock = open(LOCK, "a+", encoding="utf-8")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        lock.seek(0)
        print(f"another run is still going: {lock.read().strip()}")
        print("no request sent")
        return 3
    started = datetime.now(timezone.utc)
    lock.truncate(0)
    lock.write(f"started {started:%Y-%m-%dT%H:%M:%SZ}, pid {os.getpid()}\n")
    lock.flush()

    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown"}
    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)
    line = f"{started:%Y-%m-%dT%H:%M:%SZ}  {url}  pages={len(rows)}  {verdict}"
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(line + "\n")
    print(f"log: {line}")
    return 0 if whole else 2


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

No run recorded here sent a `user_agent` or a `delay`. Give your copy both, as in the lessons before, with your own bot name and contact address:

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

## Start it twice

Open two terminals in the same folder. In the first, start the crawl:

```bash
python3 one_at_a_time.py https://quotes.toscrape.com/
```

While it is still fetching, run this in the second:

```bash
python3 one_at_a_time.py https://quotes.toscrape.com/
echo $?
```

The recorded crawl took 2.7 seconds, so there was not much room. Your copy sends `delay`, so it pauses between requests, and that gives you longer to start the second copy.

On 2026-11-20 the first terminal started at 22:36:07 UTC, crawled 20 pages, exited 0 and printed one line:

```text
log: 2026-11-20T22:36:07Z  https://quotes.toscrape.com/  pages=20  ok
```

The second terminal started at 22:36:08, finished in a tenth of a second and exited 3:

```text
another run is still going: started 2026-11-20T22:36:07Z, pid 53456
no request sent
```

## Read the two terminals

The start time in the refusal, 22:36:07, is the same second that opens the first run's log line. The refused copy read it out of `runs/job.lock`, where the first run had written it after taking the lock. The pid tells you which process to look at if a run seems stuck.

The refused copy returned before it built a request, so nothing went to the site and nothing went into `runs/log.txt`. The log has the first run's line and no other. That is why the refusal gets its own exit code. Code 3 means no crawl happened, which is different from code 1, where a crawl was tried and failed.

The recorded runs sent no `delay`, so the overlap came from the crawl's own 2.7 seconds. A run that takes longer leaves a longer window, and the lock covers all of it, however long that turns out to be.

One limit to know. Python raises `BlockingIOError`, the `OSError` the script catches, when the error is `EWOULDBLOCK`, and that is how the refusal came through on the machine that made these runs. Python's documentation also says that "On some systems, this function is emulated using fcntl()", and there the error you get may be a different one. If your second start prints a traceback instead of the refusal, catch `OSError` there and check its `errno`.

## Put the lock into your own script

Copy your `stop_bad_run.py` from lesson 12 to `one_at_a_time.py`. Add `import fcntl` and the `LOCK` constant from the recorded script. Then find these two lines near the top of `main()`:

```python
    os.makedirs("runs", exist_ok=True)
    started = datetime.now(timezone.utc)
```

Keep the first and replace the second with the lock block, which reads the start time itself once the lock is yours:

```python
    os.makedirs("runs", exist_ok=True)
    lock = open(LOCK, "a+", encoding="utf-8")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        lock.seek(0)
        print(f"another run is still going: {lock.read().strip()}")
        print("no request sent")
        return 3
    started = datetime.now(timezone.utc)
    lock.truncate(0)
    lock.write(f"started {started:%Y-%m-%dT%H:%M:%SZ}, pid {os.getpid()}\n")
    lock.flush()
```

The block sits above the `try` that ends in lesson 11's log call, so a refused start returns before that `try` begins and its `finally` never runs. The log gets a line for every crawl and none for a start that stood aside. Your `--short` option can stay. The commands on this page do not use it.

## Try it yourself

Hold the lock with something other than the script. In the first terminal, run a Python one-liner that takes the same lock and keeps it for 30 seconds:

```bash
python3 -c 'import fcntl, time; f = open("runs/job.lock", "a+"); fcntl.flock(f, fcntl.LOCK_EX); time.sleep(30)'
```

Within those 30 seconds, start the script in the second terminal and print the exit code. The refusal will show whatever line the last real run left in the file, because the one-liner wrote nothing. The lock decides, and the line is only a note. Wait for the one-liner to end, then start the script again.

You are done when the start during the 30 seconds prints `no request sent` and `echo $?` gives 3, and the start after them crawls, prints its `ok:` or `held:` line and adds one line to `runs/log.txt`.

## Do this, avoid this

Two copies crawling at once send the site twice the requests at once, which undoes the rate you set in [lesson 4](/learn/course/pace-your-requests/). The lock keeps the job to the pace you chose. It does not decide whether the site wants the job at all; the [robots.txt](/learn/course/read-robots-txt/) file and the site's terms still do.

### Do this

- Take the lock before the script sends its first request, with LOCK_NB so a late start gives up at once.
- Open the lock file with a+, so a refused start can read the holder's line without emptying it.
- Write the start time and process id into the file only after the lock is yours.
- Exit 3 on a refused start and write nothing to runs/log.txt, since no crawl ran.

### Avoid this

- Testing whether job.lock exists. A crashed run leaves the file behind, and every later start would refuse.
- Deleting the lock file when a run ends. The lock goes with the process, and the file can stay.
- Keeping runs/ on a network share. The flock manual gives NFS and SMB rules of their own.
- Starting the refused job again in a loop. The next scheduled start will find the lock free.

## Next

The 2026-11-20 pair left one line in `runs/log.txt` and one refusal on a screen, and the site saw one crawl. With the job on a schedule and one copy at a time, the next lesson asks whether the site's robots.txt still says what it said when you first read it, and has the script check before each run.

## Sources

1. [Python documentation, fcntl: The fcntl and ioctl system calls, fcntl.flock and LOCK_NB](https://docs.python.org/3/library/fcntl.html) Read November 21, 2026
2. [Linux manual page, flock(2)](https://man7.org/linux/man-pages/man2/flock.2.html) Read November 21, 2026
