spring_boot_starter_scheduling

spring_boot_starter_scheduling runs work nobody calls: annotate a bean method with @Scheduled and the application runs it by itself, every few minutes, with a pause after each run, or at cron times such as "9:00 on working days". The TaskScheduler bean schedules work decided at runtime. It is the Dart counterpart of Spring's @Scheduled and TaskScheduler, for servers and Flutter apps alike.

Why

Refreshing a cache, syncing with a server, sending a daily digest, deleting old files: without this starter you would start Timers yourself, keep them, handle their errors and cancel them on shutdown. With it you annotate the method; the tasks start once the application is ready and stop when it closes.

Setup

# pubspec.yaml
dependencies:
  spring_boot_starter_scheduling: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # required: makes @Scheduled methods callable

There is no @EnableScheduling: the starter is found automatically. The generator is required because Dart has no reflection: it writes the code that finds and calls the @Scheduled methods. One import: package:spring_boot_starter_scheduling/spring_boot_starter_scheduling.dart, which re-exports spring_boot_dart and spring_boot_starter_logging.

Example

import 'package:spring_boot_starter_scheduling/spring_boot_starter_scheduling.dart';

import 'spring_gen/main.spring.dart';

@Component()
class Reports {
  Reports(this.repository);

  final ReportRepository repository;

  // Keeps the report cache fresh: a run starts every 5 minutes.
  @Scheduled(fixedRate: Duration(minutes: 5))
  void refreshCache() => repository.refresh();

  // Talks to a slow server: the 30 s pause starts when a sync is done.
  @Scheduled(fixedDelay: Duration(seconds: 30))
  Future<void> syncWithServer() => repository.sync();

  @Scheduled(cron: '0 0 9 * * MON-FRI') // 9:00 on working days
  void morningDigest() => repository.sendDigest();

  // Every 10 minutes unless reports.rate says otherwise.
  @Scheduled(fixedRateString: r'${reports.rate:10m}')
  void recompute() => repository.recompute();
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);

What starts

What is inside

In Spring (Java)

@EnableScheduling
@SpringBootApplication
class ReportsApplication {}

@Component
class Reports {
  @Scheduled(fixedRate = 5, timeUnit = TimeUnit.MINUTES)
  void refreshCache() { repository.refresh(); }

  @Scheduled(cron = "0 0 9 * * MON-FRI")
  void morningDigest() { repository.sendDigest(); }
}

Differences that matter:

See also