学习使用SpringBoot框架搭建项目完成一个推送消息的定时任务
参考链接:https://blog.csdn.net/baidu_39298625/article/details/98102453
SpringBoot框架的搭建(工具idea)
新建项目:
注意:链接中什么后缀都不加会自动跳转到index.html页面,推测应该是由于SpringBoot框架的默认配置。
controller中requestMapping后面的路径加入路径后面,展示的页面是return字符串对应的页面。
连接数据库失败:
jdbc:mysql://localhost:3306/task_1 ?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
数据库版本8.0.18
定时任务需要使用到cron表达式
cron表达式https://www.cnblogs.com/junrong624/p/4239517.html
定时任务,参考文章https://www.cnblogs.com/mmzs/p/10161936.html
package com.info.taskl.tasks;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration //1.主要用于标记配置类,兼备Component的效果。
public class StaticTaskDemo {
//3.添加定时任务
@Scheduled(cron="*/5 * * * * ?")
private void insertTasks(){
System.out.println("success!");
}
}
注意:注解@EnableScheduling需要放在包含有main函数的类中。这样子,项目启动后,定时任务就自动开始跑起来了。
package com.info.taskl;
import com.info.taskl.tasks.StaticTaskDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling // 2.开启定时任务
public class TasklApplication {
public static void main(String[] args) {
SpringApplication.run(TasklApplication.class, args);
}
}