TP14.4: Tarefas Agendadas
Objetivos do Exercício
- Configurar tarefas agendadas
- Utilizar expressões Cron
- Implementar relatórios automáticos
- Gerenciar tarefas assíncronas
Duração estimada: 45 min
Arquitetura
Application Spring Boot
|
+-- Scheduler Thread Pool
|
+-- Daily Report (0 0 6 * * *)
+-- Hourly Cleanup (0 0 * * * *)
+-- Price Sync (fixedRate = 60000)
+-- Health Check (fixedDelay = 30000)
Parte 1: Configuração (10 min)
1.1 Aplicação
package com.example.scheduling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}
1.2 Configuração
package com.example.scheduling.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class SchedulingConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setTaskScheduler(taskScheduler());
}
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
scheduler.setThreadNamePrefix("scheduler-");
scheduler.setErrorHandler(t -> {
System.err.println("Task error: " + t.getMessage());
});
return scheduler;
}
}
1.3 application.yml
app:
scheduling:
enabled: true
cleanup:
max-age-hours: 24
report:
email: admin@example.com
Parte 2: Tarefas Agendadas (20 min)
2.1 Serviço de Tarefas
package com.example.scheduling.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class ScheduledTaskService {
private static final Logger log = LoggerFactory.getLogger(ScheduledTaskService.class);
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final AtomicInteger taskCounter = new AtomicInteger(0);
// A cada 10 segundos
@Scheduled(fixedRate = 10000)
public void heartbeat() {
int count = taskCounter.incrementAndGet();
log.info("[Heartbeat #{}] Application is running at {}",
count, LocalDateTime.now().format(formatter));
}
// A cada 30 segundos após o término da anterior
@Scheduled(fixedDelay = 30000)
public void cleanupTask() {
log.info("[Cleanup] Starting cleanup task...");
// Simular limpeza
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
log.info("[Cleanup] Cleanup completed - {} items removed",
(int)(Math.random() * 100));
}
// A cada minuto (no início do minuto)
@Scheduled(cron = "0 * * * * *")
public void everyMinute() {
log.info("[Cron] Minute task executed at {}",
LocalDateTime.now().format(formatter));
}
// A cada 5 minutos
@Scheduled(cron = "0 */5 * * * *")
public void everyFiveMinutes() {
log.info("[Cron] Five-minute task executed");
generateQuickReport();
}
// Todos os dias às 6h da manhã
@Scheduled(cron = "0 0 6 * * *")
public void dailyReport() {
log.info("[Daily] Generating daily report...");
// Gerar relatório
log.info("[Daily] Daily report generated and sent");
}
// Todas as segundas-feiras às 9h
@Scheduled(cron = "0 0 9 * * MON")
public void weeklyReport() {
log.info("[Weekly] Generating weekly report...");
}
private void generateQuickReport() {
log.info("Quick report: Active threads = {}, Free memory = {} MB",
Thread.activeCount(),
Runtime.getRuntime().freeMemory() / (1024 * 1024));
}
// Método assíncrono
@Async
public void asyncTask(String taskName) {
log.info("[Async] Starting async task: {} on thread {}",
taskName, Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
log.info("[Async] Completed async task: {}", taskName);
}
}
2.2 Serviço de Estatísticas
package com.example.scheduling.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;
@Service
public class StatisticsService {
private static final Logger log = LoggerFactory.getLogger(StatisticsService.class);
private final AtomicLong requestCount = new AtomicLong(0);
private final AtomicLong errorCount = new AtomicLong(0);
public void incrementRequests() {
requestCount.incrementAndGet();
}
public void incrementErrors() {
errorCount.incrementAndGet();
}
// Relatório de estatísticas a cada minuto
@Scheduled(cron = "0 * * * * *")
public void reportStatistics() {
long requests = requestCount.getAndSet(0);
long errors = errorCount.getAndSet(0);
log.info("[Stats] Last minute: {} requests, {} errors, Error rate: {}%",
requests,
errors,
requests > 0 ? (errors * 100 / requests) : 0);
}
// Verificação de saúde a cada 30 segundos
@Scheduled(fixedRate = 30000)
public void healthCheck() {
Runtime runtime = Runtime.getRuntime();
long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024);
long maxMemory = runtime.maxMemory() / (1024 * 1024);
int usagePercent = (int) (usedMemory * 100 / maxMemory);
if (usagePercent > 80) {
log.warn("[Health] High memory usage: {}% ({} MB / {} MB)",
usagePercent, usedMemory, maxMemory);
} else {
log.debug("[Health] Memory usage: {}% ({} MB / {} MB)",
usagePercent, usedMemory, maxMemory);
}
}
}
Parte 3: Controller para Testes (10 min)
package com.example.scheduling.controller;
import com.example.scheduling.service.ScheduledTaskService;
import com.example.scheduling.service.StatisticsService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final ScheduledTaskService taskService;
private final StatisticsService statisticsService;
public TaskController(ScheduledTaskService taskService,
StatisticsService statisticsService) {
this.taskService = taskService;
this.statisticsService = statisticsService;
}
@PostMapping("/async/{name}")
public ResponseEntity<Map<String, String>> triggerAsyncTask(@PathVariable String name) {
taskService.asyncTask(name);
return ResponseEntity.ok(Map.of(
"message", "Async task '" + name + "' started",
"status", "RUNNING"
));
}
@GetMapping("/simulate-traffic")
public ResponseEntity<Map<String, String>> simulateTraffic(
@RequestParam(defaultValue = "100") int requests) {
for (int i = 0; i < requests; i++) {
statisticsService.incrementRequests();
if (Math.random() < 0.05) { // 5% erros
statisticsService.incrementErrors();
}
}
return ResponseEntity.ok(Map.of(
"message", requests + " requests simulated"
));
}
}
Parte 4: Testes (10 min)
4.1 Observar os Logs
Inicie a aplicação e observe os logs:
[Heartbeat #1] Application is running at 2024-01-15 10:00:00
[Cron] Minute task executed at 2024-01-15 10:01:00
[Cleanup] Starting cleanup task...
[Cleanup] Cleanup completed - 45 items removed
[Stats] Last minute: 0 requests, 0 errors, Error rate: 0%
4.2 Testar Tarefas Assíncronas
# Disparar uma tarefa assíncrona
curl -X POST http://localhost:8080/api/tasks/async/test-task-1
# Simular tráfego
curl "http://localhost:8080/api/tasks/simulate-traffic?requests=500"
4.3 Verificar as Estatísticas
Aguarde 1 minuto e observe o relatório de estatísticas nos logs.
Expressões Cron - Referência
| Expression | Descrição |
|---|---|
0 * * * * * | A cada minuto |
0 */5 * * * * | A cada 5 minutos |
0 0 * * * * | A cada hora |
0 0 6 * * * | Todos os dias às 6h |
0 0 9 * * MON | Todas as segundas às 9h |
0 0 0 1 * * | Primeiro dia do mês |
Checklist de Validação
- As tarefas agendadas executam
- Os logs mostram as execuções
- As tarefas assíncronas funcionam
- As estatísticas são calculadas