在Spring框架中,异步处理和定时任务是常见的功能,可以提高系统的性能和灵活性。
一、异步处理
-
使用步骤:
- 在Spring中使用
@Async注解来标记异步方法。 - 需要在配置类上添加
@EnableAsync注解开启异步支持。
- 在Spring中使用
-
代码如下:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void asyncMethod() {
// 异步方法
}
}
二、定时任务
-
使用步骤:
- 在Spring中使用
@Scheduled注解来标记定时任务方法。 - 需要在配置类上添加
@EnableScheduling注解开启定时任务支持。
- 在Spring中使用
-
代码如下:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
@Scheduled(fixedRate = 5000) // 每隔5秒执行一次
public void scheduledMethod() {
// 定时任务
}
}
原文链接: https://blog.csdn.net/2401_82884096/article/details/137908232