Skip to content
Skills Library
Programming · Building & coding

spring-scheduling

/spring-scheduling

Spring Scheduling and Async for Spring Boot 3.x. Covers @Scheduled, @Async, cron expressions, ThreadPoolTaskExecutor, task monitoring, distributed scheduling with ShedLock, and error handling. USE WHEN: user mentions "@Scheduled", "@Async", "cron expression Spring", "background jobs Spring", "async Spring Boot", "ThreadPoolTaskExecutor", "ShedLock" DO NOT USE FOR: complex batch jobs - use `spring-batch` skill, workflow orchestration - consider Temporal or Camunda, message-driven - use messaging skills

Licence
MIT
Last repository change
21.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
3
Scripts
0
HTML comments
0
URLs in SKILL.md
2
Deprecation

No signals detected. Repository changed on 21.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Spring Scheduling and Async for Spring Boot 3.x. Covers @Scheduled, @Async, cron expressions, ThreadPoolTaskExecutor, task monitoring, distributed scheduling with ShedLock, and error handling. USE WHEN: user mentions "@Scheduled", "@Async", "cron expression Spring", "background jobs Spring", "async Spring Boot", "ThreadPoolTaskExecutor", "ShedLock" DO NOT USE FOR: complex batch jobs - use `spring-batch` skill, workflow orchestration - consider Temporal or Camunda, message-driven - use messaging skills

Triggers from the description

@Scheduled@Asynccron expression Springbackground jobs Springasync Spring BootThreadPoolTaskExecutorShedLock
Original author description

Spring Scheduling and Async for Spring Boot 3.x. Covers @Scheduled, @Async, cron expressions, ThreadPoolTaskExecutor, task monitoring, distributed scheduling with ShedLock, and error handling. USE WHEN: user mentions "@Scheduled", "@Async", "cron expression Spring", "background jobs Spring", "async Spring Boot", "ThreadPoolTaskExecutor", "ShedLock" DO NOT USE FOR: complex batch jobs - use `spring-batch` skill, workflow orchestration - consider Temporal or Camunda, message-driven - use messaging skills

How it works

  1. Quick Start
  2. @Scheduled
  3. @Async
  4. Task Executor Configuration
  5. Best Practices
  6. Production Checklist
  7. Anti-Patterns
  8. Quick Troubleshooting
  9. Reference Documentation
Original SKILL.md headings · 234 lines, 781 words
SKILL.md preview
---
name: spring-scheduling
description: |
  Spring Scheduling and Async for Spring Boot 3.x. Covers @Scheduled, @Async,
  cron expressions, ThreadPoolTaskExecutor, task monitoring, distributed
  scheduling with ShedLock, and error handling.

  USE WHEN: user mentions "@Scheduled", "@Async", "cron expression Spring",
  "background jobs Spring", "async Spring Boot", "ThreadPoolTaskExecutor", "ShedLock"

  DO NOT USE FOR: complex batch jobs - use `spring-batch` skill,
  workflow orchestration - consider Temporal or Camunda,
  message-driven - use messaging skills
allowed-tools: Read, Grep, Glob, Write, Edit
---
# Spring Scheduling & Async

> **Full Reference**: See [async.md](async.md) for async configuration, multiple executors, and CompletableFuture patterns.
> **Full Reference**: See [distributed.md](distributed.md) for ShedLock, error handling, dynamic scheduling, and testing.

## Quick Start

```java
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {}

@Service
@Slf4j
public class ScheduledTasks {

    @Scheduled(fixedRate = 60000)  // Every minute
    public void runEveryMinute() {
        log.info("Task executed at {}", LocalDateTime.now());
    }

    @Async
    public CompletableFuture<String> asyncOperation() {
        return CompletableFuture.completedFuture("Done");
    }
}
```

---

## @Scheduled

### Fixed Rate vs Fixed Delay

```java
@Service
public class ScheduledTasks {

    // Fixed Rate: runs every 5s from start of previous
    @Scheduled(fixedRate = 5000)
    public void fixedRateTask() { }

    // Fixed Delay: runs 5s after previous completes
    @Scheduled(fixedDelay = 5000)
    public void fixedDelayTask() { }

    // Initial delay before first run
    @Scheduled(fixedRate = 5000, initialDelay = 10000)
    public void delayedStart() { }

    // Configurable via properties
    @Scheduled(fixedRateString = "${task.rate:5000}")
    public void configurableTask() { }

    // With TimeUnit
    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES)
    public void everyMinute() { }
}
```

### Cron Expressions

```java
@Service
public class CronTasks {

    // Daily at 2:00 AM
    @Scheduled(cron = "0 0 2 * * *")
    public void dailyAt2AM() { }

    // Every Monday at 9:00 AM
    @Scheduled(cron = "0 0 9 * * MON")
    public void everyMondayAt9AM() { }

    // Every 15 minutes during business hours (9-18)
    @Scheduled(cron = "0 */15 9-18 * * MON-FRI")
    public void businessHoursTask() { }

    // With timezone
    @Scheduled(cron = "0 0 9 * * *", zone = "Europe/Rome")
    public void dailyAt9AMRome() { }

    // Disable with "-"
    @Scheduled(cron = "${task.cron:-}")
    public void optionalTask() { }
}
```

### Cron Expression Reference

```
┌───────────── second (0-59)
│ ┌───────────── minute (0-59)
│ │ ┌───────────── hour (0-23)
│ │ │ ┌───────────── day of month (1-31)
│ │ │ │ ┌───────────── month (1-12 or JAN-DEC)
│ │ │ │ │ ┌───────────── day of week (0-7 or SUN-SAT)
│ │ │ │ │ │
* * * * * *
```

| Expression | Description |
|------------|-------------|
| `0 0 * * * *` | Every hour |
| `0 */10 * * * *` | Every 10 minutes |
| `0 0 8-18 * * *` | Every hour from 8 AM to 6 PM |
| `0 0 9 * * MON-FRI` | 9 AM on weekdays |
| `0 0 0 1 * *` | First day of every month |

---

## @Async

### Basic Configuration

```java
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Async-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
```

### Async Methods

```java
@Service
public class AsyncService {

    // Fire and forget
    @Async
    public void sendEmailAsync(String to, String subject, String body) {
        emailSender.send(to, subject, body);
    }

    // With result
    @Async
    public CompletableFuture<Report> generateReportAsync(ReportRequest request) {
        Report report = reportGenerator.generate(request);
        return CompletableFuture.completedFuture(report);
    }

    // With specific executor
    @Async("reportExecutor")
    public CompletableFuture<Report> generateHeavyReport(ReportRequest request) {
        return CompletableFuture.completedFuture(reportGenerator.generateHeavy(request));
    }
}
```

---

## Task Executor Configuration

```yaml
spring:
  task:
    execution:
      pool:
        core-size: 5
        max-size: 10
        queue-capacity: 100
        keep-alive: 60s
      thread-name-prefix: task-
      shutdown:
        await-termination: true
        await-termination-period: 60s

    scheduling:
      pool:
        size: 3
      thread-name-prefix: scheduling-
```

---

## Best Practices

| Do | Don't |
|----|-------|
| Use ShedLock for clustered env | Allow duplicate executions |
| Configure error handler | Ignore task exceptions |
| Monitor execution time | Deploy without metrics |
| Use CompletableFuture for results | Use void async without handler |
| Configure graceful shutdown | Kill running tasks abruptly |

## Production Checklist

- [ ] @EnableScheduling and @EnableAsync configured
- [ ] Thread pool properly sized
- [ ] ShedLock for clustered environment
- [ ] Error handling implemented
- [ ] Metrics for monitoring
- [ ] Graceful shutdown configured
- [ ] Retry for transient failures

## Anti-Patterns

| Anti-Pattern | Problem | Solution |
|--------------|---------|----------|
| Missing @EnableScheduling | Task doesn't run | Add annotation |
| Internal @Async call | Proxy bypassed | Use self-injection |
| Task overlap | Concurrent execution | Use fixed delay or ShedLock |
| Small thread pool | Thread starvation | Size pool appropriately |
| Void async without handler | Lost exceptions | Implement AsyncUncaughtExceptionHandler |

## Quick Troubleshooting

| Problem | Diagnostic | Fix |
|---------|------------|-----|
| Task not executing | Check annotations | Add @EnableScheduling |
| Async not working | Check call site | Avoid internal calls |
| Task runs multiple times | Check cluster | Add ShedLock |
| Thread pool exhausted | Check pool config | Increase pool size |

## Reference Documentation
- [Task Execution and Scheduling](https://docs.spring.io/spring-framework/reference/integration/scheduling.html)
- [ShedLock](https://github.com/lukas-krecan/ShedLock)
Files in this package (3)
  • SKILL.md 7 KB
  • async.md 6 KB
  • distributed.md 7 KB

Versions

The database has no other skills named spring-scheduling.

Database snapshot: 13.11.2026 · package version 78ca293340e6 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100cron-scheduling
    Cron and scheduled task management. node-cron, cron expressions, Spring @Scheduled, APScheduler (Python), and distributed scheduling patterns. USE WHEN: user mentions "cron", "scheduled task", "cron job", "node-cron", "@Scheduled", "APScheduler", "periodic task", "crontab" DO…
  • 100spring-batch
    Spring Batch for batch processing in Spring Boot 3.x. Covers Job, Step, ItemReader/Processor/Writer, chunk processing, job parameters, restart, skip/retry, partitioning, and monitoring. USE WHEN: user mentions "spring batch", "batch job", "ETL Spring", "ItemReader",…
  • 100scheduled-tasks
    Use when creating or reviewing @Scheduled jobs, cron/time-zone configuration, overlapping runs or multi-instance scheduling. Not for Spring Batch chunk/restart mechanics or arbitrary async dispatch.
  • 100unit-test-scheduled-async
    Provides patterns for unit testing Spring `@Scheduled` and `@Async` methods using JUnit 5, CompletableFuture, Awaitility, and Mockito. Covers mocking task execution and timing, verifying execution counts, testing cron expressions, validating retry behavior, and simulating thread…
  • 100scheduled-tasks
    Use when creating or reviewing @Scheduled jobs, cron/time-zone configuration, overlapping runs or multi-instance scheduling. Not for Spring Batch chunk/restart mechanics or arbitrary async dispatch.
  • 100cron-scheduling-stinger
    Design reliable scheduled jobs. Use for cron expressions, DST, distributed execution, retries, idempotency, or monitoring. Read README.md for the guide map.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.