且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Web应用程序中的Spring线程

更新时间:2023-01-10 09:36:23

你可以使用 @ Scheduled(fixedDelay = 5000)定期执行方法。请记住为包含main方法的类设置 @EnableScheduling

You can use @Scheduled(fixedDelay = 5000) to execute a method periodic. Remember to set @EnableScheduling for class containing your main method.

@Scheduled 注释 - fixedDelay fixedRate

fixedDelay 将在上次执行完成后延迟X毫秒继续执行您的方法。

fixedDelay will continuously execute your method with a delay of X miliseconds after the last execution has finished.

fixedRate 将在固定日期持续执行您的方法。因此,无论最后一次执行是否完成,每X毫秒都将执行此方法。

fixedRate will continuously execute your method with at a fixed date. So every X milisecond this method will be executed regardless if the last execution has finished.

您还可以使用 @Async 如果你想一次处理一堆对象。再次,您需要使用main方法将 @EnableAsync 添加到您的班级。

You can also use @Async if you want to process a bunch of objects all at once. Once again, you need to add @EnableAsync to your class with your main method.

示例

//Remember to set @EnableScheduling
//in the class containing your main method
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

@Component
public class ScheduledTasks {

List<YourObject> myObjects;

    //This method will run every 5 second.
    @Scheduled(fixedDelay = 5000)
    public void yourMethodName() {
        //This will process all of your objects all at once using treads
        for(YourObject yo : myObjects){
            yo.process();
        }
    }
}

public class YourObject {

    Integer someTest = 0;

    @Async
    public void process() {
       someTest++;
    }
}

奖金
您可以通过扩展 AsyncConfigurerSupport 并覆盖 getAsyncExecutor 来删除池大小的XML配置。有关此方法的更多信息,请访问以下链接

Bonus You can get rid of your XML configuration for the pool size by extending AsyncConfigurerSupport and override getAsyncExecutor. More information about this approach can be found at the below links

我建议您查看:

https://spring.io/guides/gs/scheduling-tasks/

https:// spring。 io / guides / gs / async-method /