Complete the code to schedule a method to run every 5 seconds.
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TaskScheduler { @Scheduled(fixedRate = [1]) public void runTask() { System.out.println("Task executed"); } }
The fixedRate attribute expects milliseconds. To run every 5 seconds, use 5000.
Complete the code to schedule a method to run every day at 2:30 AM.
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class DailyTask { @Scheduled(cron = [1]) public void runDaily() { System.out.println("Daily task executed"); } }
The cron expression "0 30 2 * * ?" means at second 0, minute 30, hour 2 every day.
Fix the error in the code to enable scheduling in the Spring Boot application.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication [1] public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
The @EnableScheduling annotation enables Spring's scheduled task execution capability.
Fill both blanks to create a scheduled method that runs every minute and logs the current time.
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalTime; @Component public class ClockTask { @Scheduled(cron = [1]) public void logTime() { System.out.println("Current time: " + LocalTime.[2]()); } }
The cron expression '0 * * * * ?' runs the method every minute at second 0. The LocalTime.now() method gets the current time.
Fill all three blanks to create a scheduled task that runs every 10 seconds, prints a message, and uses a component annotation.
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.[1].Component; @[2] public class MessageTask { @Scheduled(fixedRate = [3]) public void printMessage() { System.out.println("Hello every 10 seconds"); } }
The @Component annotation marks the class as a Spring bean. It is imported from org.springframework.stereotype.Component. The fixedRate is set to 10000 milliseconds for 10 seconds.