Saltar al contenido principal

TP14.4: Tareas Programadas

Objetivos del TP​

  • Configurar las tareas programadas
  • Utilizar expresiones Cron
  • Implementar informes automáticos
  • Gestionar tareas asíncronas

Duración estimada: 45 min


Arquitectura​

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: Configuración (10 min)​

1.1 Aplicación​

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 Configuración​

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: Tareas Programadas (20 min)​

2.1 Servicio de Tareas​

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);

// 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));
}

// Cada 30 segundos después de finalizar la anterior
@Scheduled(fixedDelay = 30000)
public void cleanupTask() {
log.info("[Cleanup] Starting cleanup task...");

// Simular limpieza
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

log.info("[Cleanup] Cleanup completed - {} items removed",
(int)(Math.random() * 100));
}

// Cada minuto (al inicio del minuto)
@Scheduled(cron = "0 * * * * *")
public void everyMinute() {
log.info("[Cron] Minute task executed at {}",
LocalDateTime.now().format(formatter));
}

// Cada 5 minutos
@Scheduled(cron = "0 */5 * * * *")
public void everyFiveMinutes() {
log.info("[Cron] Five-minute task executed");
generateQuickReport();
}

// Todos los días a las 6 de la mañana
@Scheduled(cron = "0 0 6 * * *")
public void dailyReport() {
log.info("[Daily] Generating daily report...");
// Generar informe
log.info("[Daily] Daily report generated and sent");
}

// Todos los lunes a las 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 así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 Servicio de Estadí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();
}

// Informe de estadísticas 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);
}

// Verificación de salud 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: Controlador para Pruebas (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% errores
statisticsService.incrementErrors();
}
}

return ResponseEntity.ok(Map.of(
"message", requests + " requests simulated"
));
}
}

Parte 4: Pruebas (10 min)​

4.1 Observar los Logs​

Inicie la aplicación y observe los 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 Probar las Tareas Async​

# Disparar una tarea async
curl -X POST http://localhost:8080/api/tasks/async/test-task-1

# Simular tráfico
curl "http://localhost:8080/api/tasks/simulate-traffic?requests=500"

4.3 Verificar las Estadísticas​

Espere 1 minuto y observe el informe de estadísticas en los logs.


Expresiones Cron - Referencia​

ExpresiónDescripción
0 * * * * *Cada minuto
0 */5 * * * *Cada 5 minutos
0 0 * * * *Cada hora
0 0 6 * * *Todos los días a las 6h
0 0 9 * * MONTodos los lunes a las 9h
0 0 0 1 * *Primer día del mes

Checklist de Validación​

  • Las tareas programadas se ejecutan
  • Los logs muestran las ejecuciones
  • Las tareas async funcionan
  • Las estadísticas se calculan

Volver al Módulo 14

Volver al inicio