Camel timer and scheduler: starting routes on a schedule

Some routes are not started by a message but by the clock: a heartbeat, a nightly export, a poll of a system that cannot push. Camel has two components for that, timer and scheduler, built on different JDK classes. This page explains how each one fires, then runs both with Camel 4.23 to show periods, catching up after a slow run, threads shared by timer name, thread pools and cron expressions.

Contents

How Camel starts a route from the clock

Most routes start when a message arrives. A scheduled route starts itself: a consumer endpoint creates an empty exchange at set times and sends it down the route. The route then does whatever the job is, such as polling a database with pollEnrich, calling an API or writing a report.

Camel has two components for this, and they differ in what runs them underneath:

  • timer: built on java.util.Timer. Each timer name gets one Timer, which means one thread. Simple and light, it suits heartbeats and fixed-interval jobs.
  • scheduler: built on a ScheduledExecutorService, the same machinery as Camel's polling consumers such as file and FTP. It has a configurable thread pool, back-off when idle or failing, and, with camel-spring or camel-quartz on the classpath, cron expressions.

Both are in camel-core. For calendar-style schedules, the separate camel-quartz component offers the quartz: endpoint with cron triggers and clustering through a database.

Scheduling options in Camel
EndpointRuns onMain options (default)Best for
timer:namejava.util.Timer, one thread per nameperiod (1000 ms), delay (1000 ms), repeatCount (0, forever), fixedRate (false)Heartbeats, simple intervals, one-off startup jobs
scheduler:nameScheduledExecutorServicedelay (500 ms), initialDelay (1000 ms), poolSize (1), useFixedDelay (true)Polling jobs, back-off, cron via scheduler=spring
quartz:group/nameQuartz scheduler (camel-quartz)cron, trigger.repeatIntervalCalendar schedules, clustered jobs

The examples run with Camel 4.23 on Java 21, with camel-main and the core components; the cron example adds camel-spring and Spring Framework 7.0. The programs collect each run in a mock endpoint or a list and print afterwards, and they round times, since the clock never fires at exactly the same millisecond twice.

Timer basics: period, delay and repeatCount

A heartbeat that fires four times, 300 ms apart, starting at once, shows the options and the information the timer puts on each exchange. A second timer without includeMetadata shows what is missing by default:

Java
import java.util.Date;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;

public class TimerBasics {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("timer:heartbeat?delay=0&period=300&repeatCount=4&includeMetadata=true")
                .process(e -> e.setProperty("thread", Thread.currentThread().getName()))
                .to("mock:ticks");
            from("timer:plain?delay=0&repeatCount=1")
                .to("mock:plain");
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        MockEndpoint ticks = camel.getEndpoint("mock:ticks", MockEndpoint.class);
        ticks.expectedMessageCount(4);
        MockEndpoint plain = camel.getEndpoint("mock:plain", MockEndpoint.class);
        plain.expectedMessageCount(1);
        camel.addRoutes(new Routes());
        camel.start();
        ticks.assertIsSatisfied(5000);
        plain.assertIsSatisfied(5000);

        long first = 0;
        for (Exchange tick : ticks.getExchanges()) {
            long fired = tick.getMessage().getHeader(Exchange.TIMER_FIRED_TIME, Date.class)
                .getTime();
            first = first == 0 ? fired : first;
            System.out.printf("counter=%s name=%s period=%s fired at +%d ms (rounded) body=%s%n",
                tick.getProperty(Exchange.TIMER_COUNTER), tick.getProperty(Exchange.TIMER_NAME),
                tick.getProperty(Exchange.TIMER_PERIOD), Math.round((fired - first) / 100.0) * 100,
                tick.getMessage().getBody());
        }
        String thread = ticks.getExchanges().get(0).getProperty("thread", String.class);
        System.out.println("thread: " + thread.replaceAll("#\\d+", "#N"));
        Thread.sleep(500);
        System.out.println("ticks after repeatCount was reached: "
            + (ticks.getReceivedCounter() - 4));

        Exchange bare = plain.getExchanges().get(0);
        System.out.println("without includeMetadata: headers=" + bare.getMessage().getHeaders()
            + " counter=" + bare.getProperty(Exchange.TIMER_COUNTER));
        camel.stop();
    }
}
Output
counter=1 name=heartbeat period=300 fired at +0 ms (rounded) body=null
counter=2 name=heartbeat period=300 fired at +300 ms (rounded) body=null
counter=3 name=heartbeat period=300 fired at +600 ms (rounded) body=null
counter=4 name=heartbeat period=300 fired at +900 ms (rounded) body=null
thread: Camel (camel-1) thread #N - timer://heartbeat
ticks after repeatCount was reached: 0
without includeMetadata: headers={} counter=null
  • The four ticks fired at about 0, 300, 600 and 900 ms. delay=0 removed the default one-second wait before the first tick.
  • The counter, timer name and period are exchange properties, CamelTimerCounter, CamelTimerName and CamelTimerPeriod, and the fire time is also a header, CamelTimerFiredTime. In Simple, read the counter as ${exchangeProperty.CamelTimerCounter}.
  • The body is null. A timer only starts the route; set a body with setBody or fetch one with pollEnrich.
  • All ticks ran on Camel (camel-1) thread #N - timer://heartbeat, a thread named after the timer. The program replaces the thread number with N, since it depends on the order in which Camel creates threads.
  • After repeatCount=4 was reached, no more ticks came. The route stays started but idle.
  • Without includeMetadata=true, the exchange had no headers and no counter. Leaving the metadata off is the default because it saves work on very frequent timers.

timer:startup?repeatCount=1&delay=0 is a common way to run a job once when the application starts, such as loading a cache. Since the timer thread is a daemon thread by default (daemon=true), a timer does not keep the JVM alive on its own; Camel Main or Spring Boot does that.

Slow runs: fixed delay and fixed rate

A timer never starts a run while the previous run of the same timer is still going, because one thread does all the work. What happens after a slow run depends on fixedRate. Here the first run of a 250 ms timer takes a full second, and the rest are instant:

Java
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class FixedRate {

    static final List<Long> STARTS = new CopyOnWriteArrayList<>();
    static long start;

    static class Routes extends RouteBuilder {
        private final String uri;

        Routes(String uri) {
            this.uri = uri;
        }

        @Override
        public void configure() {
            from(uri)
                .process(e -> {
                    if (STARTS.isEmpty()) {
                        start = System.nanoTime();
                    }
                    STARTS.add((System.nanoTime() - start) / 1000000);
                    if (STARTS.size() == 1) {
                        Thread.sleep(1000);
                    }
                });
        }
    }

    public static void main(String[] args) throws Exception {
        for (boolean fixedRate : new boolean[] {false, true}) {
            STARTS.clear();
            CamelContext camel = new DefaultCamelContext();
            camel.addRoutes(new Routes("timer:job?delay=0&period=250&fixedRate=" + fixedRate));
            camel.start();
            while (STARTS.size() < 6) {
                Thread.sleep(10);
            }
            camel.stop();
            List<Long> rounded = STARTS.subList(0, 6).stream()
                .map(ms -> Math.round(ms / 250.0) * 250).toList();
            System.out.println("fixedRate=" + fixedRate
                + ", first 6 run starts, ms, rounded to 250: " + rounded);
        }
    }
}
Output
fixedRate=false, first 6 run starts, ms, rounded to 250: [0, 1000, 1250, 1500, 1750, 2000]
fixedRate=true, first 6 run starts, ms, rounded to 250: [0, 1000, 1000, 1000, 1000, 1250]
  • With the default fixedRate=false, the second run started as soon as the slow one ended, at 1000 ms, and the timer then went on at 250 ms intervals: 1250, 1500, 1750 and 2000. The ticks due at 250, 500 and 750 ms, during the slow run, were simply skipped.
  • With fixedRate=true, the timer tried to keep its original schedule of one run every 250 ms from the start. It had missed the runs due at 250, 500 and 750 ms, so at 1000 ms it ran four times back to back to catch up, and then continued at 1250.

Fixed delay suits jobs where only the latest run matters, such as refreshing a cache or polling for new data. Fixed rate suits jobs where the count of runs matters, such as sampling a meter every second, but a long pause, for example a garbage collection or a laptop waking from sleep, then causes a burst of catch-up runs that the downstream system has to absorb.

Timers with the same name share a thread

The thread belongs to the timer name, not to the route. Two routes that use the same name share one thread, so a slow route delays the other. Each setup here has a route that takes 600 ms per run and a route that should tick every 100 ms:

Java
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class SharedTimerThread {

    static final AtomicInteger FAST_TICKS = new AtomicInteger();

    static class Routes extends RouteBuilder {
        private final String slowTimer;
        private final String fastTimer;

        Routes(String slowTimer, String fastTimer) {
            this.slowTimer = slowTimer;
            this.fastTimer = fastTimer;
        }

        @Override
        public void configure() {
            from("timer:" + slowTimer + "?delay=0&period=100")
                .process(e -> Thread.sleep(600));
            from("timer:" + fastTimer + "?delay=0&period=100")
                .process(e -> FAST_TICKS.incrementAndGet());
        }
    }

    public static void main(String[] args) throws Exception {
        String[][] setups = {{"jobs", "jobs"}, {"report", "heartbeat"}};
        for (String[] names : setups) {
            FAST_TICKS.set(0);
            CamelContext camel = new DefaultCamelContext();
            camel.addRoutes(new Routes(names[0], names[1]));
            camel.start();
            Thread.sleep(1200);
            camel.stop();
            String verdict = FAST_TICKS.get() >= 8 ? "about every 100 ms" : "held up";
            System.out.printf("slow timer '%s', fast timer '%s': fast route ran %s%n",
                names[0], names[1], verdict);
        }
    }
}
Output
slow timer 'jobs', fast timer 'jobs': fast route ran held up
slow timer 'report', fast timer 'heartbeat': fast route ran about every 100 ms
  • When both routes used timer:jobs, the fast route was held up, because the slow route's 600 ms runs occupied the one thread that fires both timers.
  • With different names, timer:report and timer:heartbeat, each had its own thread, and the fast route ticked about every 100 ms while the slow one worked.

Give every timer its own name unless the routes are meant to be serialised. It is easy to copy a route and keep timer:tick, and the slowdown it causes appears only under load. A heartbeat that drives a health check should never share a thread with real work.

The scheduler component and its thread pool

The scheduler component runs on a ScheduledExecutorService, with options taken from Camel's polling consumers. This route runs every 100 ms after the previous run ends, each run takes 200 ms, and the pool has two threads:

Java
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class SchedulerComponent {

    static final Set<String> THREADS = ConcurrentHashMap.newKeySet();
    static final AtomicInteger RUNS = new AtomicInteger();
    static final AtomicInteger ACTIVE = new AtomicInteger();
    static final AtomicInteger PEAK = new AtomicInteger();

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("scheduler:poller?initialDelay=0&delay=100&poolSize=2")
                .routeId("poller")
                .process(e -> {
                    PEAK.accumulateAndGet(ACTIVE.incrementAndGet(), Math::max);
                    THREADS.add(Thread.currentThread().getName());
                    RUNS.incrementAndGet();
                    Thread.sleep(200);
                    ACTIVE.decrementAndGet();
                });
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        Thread.sleep(1350);
        camel.getRouteController().stopRoute("poller");
        System.out.println("pool threads that ran the route: between 1 and 2: "
            + (THREADS.size() >= 1 && THREADS.size() <= 2));
        System.out.println("most runs at the same time: " + PEAK.get());
        System.out.println("runs in about 1.35 s with a 200 ms task and delay=100: " + RUNS.get());
        camel.stop();
    }
}
Output
pool threads that ran the route: between 1 and 2: true
most runs at the same time: 1
runs in about 1.35 s with a 200 ms task and delay=100: 5
  • Runs may land on either of the two pool threads, but there was never more than one run at a time. A scheduled consumer does not start a new run while the previous one is still going, so a larger pool does not make one schedule run in parallel.
  • There were 5 runs in about 1.35 s. Each cycle took the 200 ms run plus the 100 ms delay, so a run started about every 300 ms. With the default useFixedDelay=true, the delay counts from the end of one run to the start of the next.

The scheduler also accepts the polling consumer's back-off options, backoffMultiplier, backoffIdleThreshold and backoffErrorThreshold. After the set number of idle or failed runs in a row, it skips the number of runs given by the multiplier, which saves work while a source is empty or down. greedy=true does the opposite and runs again at once while there is work. Both make the scheduler the better choice for polling, and the timer the simpler one for plain intervals.

Cron expressions

Business schedules are rarely "every N milliseconds". They are "at 02:00 every night" or "every 15 minutes during office hours", which is what cron expressions describe. The scheduler component accepts one when a cron-capable scheduler is plugged in: scheduler=spring with camel-spring, or scheduler=quartz with camel-quartz. This program uses Spring's cron, which has a seconds field, set to fire every second:

Java
import java.time.Duration;
import java.time.LocalTime;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;

public class CronSchedule {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("scheduler:nightly?scheduler=spring&scheduler.cron=*/1 * * * * *")
                .process(e -> e.getMessage().setBody(LocalTime.now()))
                .to("mock:runs");
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        MockEndpoint runs = camel.getEndpoint("mock:runs", MockEndpoint.class);
        runs.expectedMinimumMessageCount(3);
        camel.addRoutes(new Routes());
        camel.start();
        runs.assertIsSatisfied(5000);
        camel.stop();

        LocalTime previous = null;
        for (Exchange run : runs.getExchanges().subList(0, 3)) {
            LocalTime at = run.getMessage().getBody(LocalTime.class);
            String gap = previous == null ? "first run" : Math.round(
                Duration.between(previous, at).toMillis() / 1000.0) + " s after the last";
            System.out.println("run at second fraction ." + at.getNano() / 100000000
                + ", " + gap);
            previous = at;
        }
    }
}
Output
run at second fraction .0, first run
run at second fraction .0, 1 s after the last
run at second fraction .0, 1 s after the last
  • Every run started in the first tenth of a second, .0, because a cron schedule fires at calendar times, not at an offset from when the route started.
  • The runs were 1 s apart, as */1 * * * * * says.

Spring's cron format has six fields, starting with seconds: 0 0 2 * * * is 02:00:00 every day, and 0 */15 8-18 * * MON-FRI is every 15 minutes from 08:00 to 18:45 on weekdays. Quartz uses a similar format with an extra optional year field, and writes ? in either the day-of-month or the day-of-week field. Both use the JVM's default time zone unless configured otherwise. Check how your scheduler handles the hour that is skipped or repeated when the clocks change, or schedule critical jobs in UTC.

Scheduled routes in a cluster

Every instance of an application runs its own timers. With three replicas behind a load balancer, a nightly export scheduled with timer or scheduler runs three times. Options, none of them run on this page:

  • Quartz with a database job store: camel-quartz can store triggers in a database, and the Quartz cluster then makes sure only one node fires each job.
  • Camel master component: master:lock-name:timer:export runs the wrapped consumer on one node only, using a cluster service such as Kubernetes leases, ZooKeeper or a file lock.
  • An external scheduler: a Kubernetes CronJob or a workflow tool calls the application, and the route starts from a direct or HTTP endpoint instead of a timer.

Whichever you choose, make the job safe to run twice, with an idempotent consumer or a database check, because failover can still cause an occasional double run.

Choosing a scheduler

Which endpoint to use for which schedule
ScheduleEndpoint
Heartbeat or fixed intervaltimer:name?period=..., one name per route
Run once at startuptimer:name?repeatCount=1&delay=0
Fixed number of runs per time unittimer with fixedRate=true
Polling a source, with back-off when idlescheduler:name with backoffMultiplier and backoffIdleThreshold
Calendar times, such as nightly at 02:00scheduler with scheduler=spring and scheduler.cron, or quartz
One run across a clusterClustered Quartz, the master component, or an external scheduler

A scheduled route is an ordinary route once it has started, so the rest of Camel applies: use a throttler when each run fans out into many calls, and error handling so that one failed run is logged and the next run still happens. Camel Main, shown on the introduction page, keeps a plain Java application alive for its timers.