"@Scheduled" Annotation Should Only Be Applied to No-Arg Methods
What is it?
This practice targets methods in Java Spring applications annotated with @Scheduled
that incorrectly use method arguments, which can lead to runtime errors.
Why apply it?
According to Spring documentation, the @Scheduled
annotation should only be applied to no-argument methods. Violating this can result in runtime errors, which affects the reliability of the application.
How to fix it?
Transform any method annotated with @Scheduled
to a no-argument method to avoid runtime errors and ensure compliance with Spring's guidelines.
Examples
Example 1:
Negative
The negative example incorrectly adds a parameter to a method meant for @Scheduled
, which will not execute properly.
public class IncorrectScheduledService {
@Scheduled(fixedRate = 10000)
public void processFiles(String directoryPath) { /* Noncompliant */
System.out.println("Processing files in directory: " + directoryPath);
// Logic for file processing
}
private void helperMethod(String directoryPath) {
// Helper logic using the directory path
}
}
Example 2:
Positive
The positive example transforms a scheduled task into a no-argument method, ensuring it will run without errors.
public class PositiveExampleService {
@Scheduled(cron = "0 0 * * * ?")
public void scheduledTask() { /* Compliant */
System.out.println("Performing scheduled task...");
// Other task implementation logic
}
public void otherMethod() {
// Method logic that might involve parameters
}
}
Negative
The negative example demonstrates an incorrect usage of @Scheduled with a method that includes arguments, leading to runtime issues.
public class NegativeExampleService {
@Scheduled(cron = "0 0 * * * ?")
public void scheduledTask(String param) { /* Noncompliant */
System.out.println("Scheduled task with param: " + param);
// Task implementation
}
public void otherMethod(String param) {
// Method logic involving the parameter
}
}
Example 3:
Positive
This positive example shows another correct application of a no-arg method for a fixed rate scheduled task.
public class CorrectScheduledService {
@Scheduled(fixedRate = 10000)
public void processFiles() { /* Compliant */
System.out.println("Processing files at fixed rate...");
// Logic for file processing
}
private void helperMethod() {
// Helper logic if needed
}
}