SpringFrameworkSpringBoot极简教程 · Spring Boot

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

2016-04-25  本文已影响5872人  Devid

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

上一篇 下一篇

猜你喜欢

热点阅读