Graceful shutdown | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Advanced-usage  Graceful shutdown

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  Graceful shutdown    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Graceful shutdown
=================

###  On this page 

1. [ Handling Ctrl+C and SIGTERM ](#content-handling-ctrlc-and-sigterm)
2. [ Stopping after a completed page ](#content-stopping-after-a-completed-page)
3. [ Resuming after shutdown ](#content-resuming-after-shutdown)

Call `Crawl::cancel()` or cancel a clone of `Crawl::cancellation_token()` to interrupt an execution. Then keep draining the stream. The scheduler recovers unfinished claims, records elapsed time, and emits `Finished` with `FinishReason::Cancelled` unless cleanup itself fails.

Cancellation does not wait for every HTTP request to complete normally. It drops pending async processing and requeues unfinished claims. A blocking extractor or backend operation may continue after its future is dropped. Allow cleanup to finish before shutting down the Tokio runtime or reopening a checkpoint.

Handling Ctrl+C and SIGTERM
---------------------------------------------------------------------------------------------------------------------------------------

Unlike the PHP crawler's automatic `pcntl` integration, the Rust library installs no signal handlers. The executable handles Ctrl+C and, on Unix, SIGTERM. Library users choose how application signals map to cancellation.

This example handles Ctrl+C on every supported platform and SIGTERM on Unix. Your application's Tokio dependency needs the `signal` feature in addition to `macros` and `rt-multi-thread`.

```
use spatie_crawler::{CrawlEvent, Crawler, FinishReason, SqliteStore};

async fn shutdown_signal() -> std::io::Result {
    #[cfg(unix)]
    {
        let mut terminate =
            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
        tokio::select! {
            result = tokio::signal::ctrl_c() => result,
            _ = terminate.recv() => Ok(()),
        }
    }
    #[cfg(not(unix))]
    {
        tokio::signal::ctrl_c().await
    }
}

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .store(SqliteStore::open("crawl.sqlite")?)
        .build()?
        .crawl();
    let shutdown = shutdown_signal();
    tokio::pin!(shutdown);
    let mut cancelling = false;

    loop {
        tokio::select! {
            result = &mut shutdown, if !cancelling => {
                result?;
                crawl.cancel();
                cancelling = true;
            }
            event = crawl.next() => {
                let Some(event) = event else { break };
                match event {
                    CrawlEvent::Finished { reason, error, .. } => {
                        if reason == FinishReason::Cancelled {
                            eprintln!("Crawl cancelled; unfinished URLs can be resumed");
                        }
                        if let Some(error) = error {
                            eprintln!("Crawl cleanup failed: {error}");
                        }
                    }
                    other => println!("{other:?}"),
                }
            }
        }
    }
    Ok(())
}
```

The signal branch runs only once. After cancellation the event branch continues until `next()` returns `None`; it does not break at `Finished`. A bounded event channel needs a consumer, including during shutdown. Slow output and observers can delay final-event delivery.

To cancel from another task, clone `crawl.cancellation_token()` before moving the stream and call `token.cancel()` from that task. Dropping the stream also requests cancellation, but cannot await recovery or guarantee receipt of the final event. Do not drop the stream as your normal shutdown procedure.

Stopping after a completed page
-----------------------------------------------------------------------------------------------------------------------------------------------------

If you want the current handled page committed and emitted before stopping, return `PageAction::Stop` from a [custom handler](custom-request-handlers), or use `stop_when` to inspect progress between jobs. Both finish with `FinishReason::Stopped`. Concurrency means other requests may already be in flight; their unfinished claims are recovered rather than drained to normal completion.

Resuming after shutdown
-----------------------------------------------------------------------------------------------------------------------------

Reopen the checkpoint with the same seed and configuration after the scheduler releases it. SQLite's exclusive `.lock` lease prevents concurrent opens; shared references can keep that lease alive after the stream ends. Recovery preserves terminal URLs and requeues in-flight ones. See [crawling across requests](crawling-across-requests).

SIGKILL, process crashes, and runtime termination do not run graceful cleanup. Startup recovery handles abandoned claims, but elapsed time from the interrupted execution may not have been saved. Persisted attempt budgets remain consumed. Completion commits before event emission, so checkpoint recovery is not an exactly-once output guarantee.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
