您当前的位置: 首页 >  spring

java持续实践

暂无认证

  • 2浏览

    0关注

    746博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot实现定时任务

java持续实践 发布时间:2018-12-15 14:27:39 ,浏览量:2

文章目录
      • pom文件
      • 主启动类
      • 在service类写定时任务的方法
开发环境

  • JDK 1.8
  • springboot版本 1.5.12 springboot实现定时任务相当简单, 只需两步.
pom文件


	4.0.0

	com.thc
	springboot-04-task
	0.0.1-SNAPSHOT
	jar

	springboot-06-task
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.12.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-mail
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	




主启动类

在启动类加上如下的注解 @EnableScheduling 表示开启基于注解的定时任务

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

//开启基于注解的定时任务
@EnableScheduling 
@SpringBootApplication
public class Springboot04TaskApplication {

	public static void main(String[] args) {
		SpringApplication.run(Springboot04TaskApplication.class, args);
	}
}
在service类写定时任务的方法

在方法上加上@Scheduled ,表示这是一个定时任务的方法. 后面写上定时任务的表达式. 关于定时任务的表达式,可以看我另一篇文章. https://blog.csdn.net/qq_33229669/article/details/85013881 也可以在如下的网页中,进行定时任务的在线生成. 要去掉最后一位年. 因为spring的cron表达式,只支持 秒分时日月星期, 六位. 如果是七位会报错 http://cron.qqe2.com/

@Service
public class ScheduledService {
	@Scheduled(cron = "* * * * * ?")
    public void hello(){
        System.out.println("hello ... ");
    }
}

启动工程后,效果如下图

关注
打赏
1658054974
查看更多评论
立即登录/注册

微信扫码登录

0.0415s