Spring 4 通过@Scheduled注解创建定时任务

文档地址: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版本是不需要这个注解。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容