0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Планирование с помощью @Scheduled

Запускайте задачи с заданным интервалом или по расписанию cron

«Планирование с помощью @Scheduled» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Scheduling in Spring Boot

Spring Boot lets you run methods automatically on a schedule without any external cron daemon. You annotate a method with @Scheduled and Spring invokes it repeatedly in the background.

  • Perfect for cleanup jobs, polling, report generation
  • No extra infrastructure needed

Enabling scheduling

Scheduling is off by default. You turn it on with @EnableScheduling on a configuration class (often the main application class).

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableScheduling
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

fixedRate

fixedRate runs the method at a fixed interval measured from the start of one run to the start of the next. The value is in milliseconds.

@Component
public class RateTask {

    @Scheduled(fixedRate = 5000)
    public void report() {
        System.out.println("Runs every 5 seconds");
    }
}

fixedDelay

fixedDelay waits a fixed gap after the previous run finishes before starting the next one. Use it when runs must never overlap.

@Scheduled(fixedDelay = 5000)
public void process() {
    // next run starts 5s AFTER this one ends
    doWork();
}

fixedRate vs fixedDelay

The key difference is the reference point:

  • fixedRate = interval between start times (can overlap if a run is slow)
  • fixedDelay = gap between end and next start (never overlaps)

initialDelay

initialDelay delays the first execution after startup. Combine it with fixedRate or fixedDelay to avoid running immediately on boot.

@Scheduled(initialDelay = 10000, fixedRate = 5000)
public void warmThenRun() {
    // waits 10s after startup, then every 5s
}

cron expressions

For calendar-based scheduling use cron. Spring cron has 6 fields: second, minute, hour, day-of-month, month, day-of-week.

@Scheduled(cron = "0 0 9 * * MON-FRI")
public void weekdayMorning() {
    // 09:00:00 every weekday
}

Reading cron fields

An asterisk * means "every value". A ? can be used in day-of-month or day-of-week when one is unspecified. Ranges (MON-FRI), lists (1,15) and steps (*/10) are supported.

@Scheduled(cron = "*/30 * * * * *") // every 30 seconds
public void everyHalfMinute() { }

@Scheduled(cron = "0 0 0 1 * *") // midnight on the 1st of every month
public void monthly() { }

Time zones

By default cron uses the server time zone. Set zone to make schedules explicit and predictable across environments.

@Scheduled(cron = "0 0 8 * * *", zone = "Europe/Istanbul")
public void eightAmIstanbul() { }

Externalizing the schedule

Hardcoding intervals is inflexible. Use a property placeholder so the schedule can change per environment without recompiling.

@Scheduled(fixedRateString = "${app.report.rate:5000}")
public void report() { }

// application.yml
// app:
//   report:
//     rate: 10000

Scheduling pitfalls

By default a single thread runs all scheduled tasks, so a slow task can delay others. For parallel execution configure a ThreadPoolTaskScheduler. Also keep scheduled methods idempotent in case of restarts.

Quick Check

Test your understanding of scheduling.

Recap

You learned how to schedule work in Spring Boot:

  • @EnableScheduling turns the feature on
  • fixedRate = start-to-start, fixedDelay = end-to-start
  • cron handles calendar schedules; set zone for clarity
  • Externalize intervals with property placeholders

Часто задаваемые вопросы

Урок «Планирование с помощью @Scheduled» бесплатный?

Да — полный текст урока «Планирование с помощью @Scheduled» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Планирование с помощью @Scheduled»?

Запускайте задачи с заданным интервалом или по расписанию cron Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Планирование с помощью @Scheduled»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Планирование с помощью @Scheduled
  2. Задания и шаги Spring Batch
  3. Читатели, обработчики и записывающие компоненты
  4. Перезапуск и обработка ошибок
← Назад к Spring Boot 4 Microservices & REST APIs