文档地址:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling
创建方法其实很简单:
首先我们需要引入spring-context-support
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
然后创建一个任务类,在方法上加入@Scheduled
注解即可!
@Component
@EnableScheduling
public class WxTask {
@Autowired
private WxCpService wxCpService;
@Scheduled(cron = "0/5 * * * * ?")
public void sendMessage(){
WxCpMessage message = WxCpMessage
.TEXT()
.agentId("7")
.toUser("devid")
.content("提醒你打分了!")
.build();
try {
wxCpService.messageSend(message);
} catch (WxErrorException e) {
e.printStackTrace();
}
}
}
这地方要注意的是@EnableScheduling
注解,在4.x版本是必须要加的,否则任务不会生效,spring 3.x版本是不需要这个注解。