springboot:spring task定时任务

项目地址:https://github.com/snjl/springboot.springtask.git

创建一个项目,在DemoApplication上加上注解@EnableScheduling:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.demo;

import com.example.demo.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
@Autowired
private Task task;

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

在demo包里创建Task.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.example.demo.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Task {
private int count=0;

@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("[" + Thread.currentThread().getName() + "]" + "this is scheduler task runing "+(count++));
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}
}

使用@Scheduled注解,就会定时执行。

log日志:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[scheduling-1]this is scheduler task runing  0
[scheduling-1]this is scheduler task runing 1
[scheduling-1]this is scheduler task runing 2
[scheduling-1]this is scheduler task runing 3
[scheduling-1]this is scheduler task runing 4
[scheduling-1]this is scheduler task runing 5
[scheduling-1]this is scheduler task runing 6
[scheduling-1]this is scheduler task runing 7
[scheduling-1]this is scheduler task runing 8
[scheduling-1]this is scheduler task runing 9
[scheduling-1]this is scheduler task runing 10
[scheduling-1]this is scheduler task runing 11
[scheduling-1]this is scheduler task runing 12
[scheduling-1]this is scheduler task runing 13
[scheduling-1]this is scheduler task runing 14
[scheduling-1]this is scheduler task runing 15
[scheduling-1]this is scheduler task runing 16
[scheduling-1]this is scheduler task runing 17
[scheduling-1]this is scheduler task runing 18
[scheduling-1]this is scheduler task runing 19
[scheduling-1]this is scheduler task runing 20
[scheduling-1]this is scheduler task runing 21

不需要加入其它配置文件和注解。

-------------本文结束 感谢您的阅读-------------