标签:obd pattern hide exce let second text 被垃圾回收 启动
一:相关依赖与环境
<dependencies> <!--核心包--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <!--工具包--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.3.0</version> </dependency> <!--log4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
日志文件:log4j.properties
log4j.rootLogger=debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%d{yyyy-MM-dd HH/:mm/:ss}]%-5p %c(line/:%L) %x-%m%n
二.自定义Job类实现org.quartz.Job
Job:工作任务调度的接口,需要实现execute方法,在该方法中编写任务执行的业务逻辑
/** * 需要实现Job接口 */ public class HelloJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime time = LocalDateTime.now(); String localTime = df.format(time); System.out.println("数据库备份时间:"+localTime); } }
三.编写trigger和scheduler测试
public static void main(String[] args) throws SchedulerException { //调度器(Scheduler) //从工厂中获取 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //任务实例(JobDetail) JobDetail jobDetail = JobBuilder.newJob(HelloJob.class) .withIdentity("job1", "group1") //参数一:任务名称 参数二:任务组 .build(); //触发器(Trigger) SimpleTrigger trigger = TriggerBuilder.newTrigger() .withIdentity("trigger1", "group1") .startNow()//立即启用 .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(5)) //每5秒执行一次 .build(); //关联触发器和任务 按照触发器的条件执行任务 scheduler.scheduleJob(jobDetail,trigger); //启动 scheduler.start(); }
运行结果:每五秒执行一次Job
Job生命周期:从日志中可以看出,每一次调度器执行Job时,都会创建一个新的Job实例。实际上,当execute方法执行完成后,相关的Job实例会被释放,释放的Job实例被垃圾回收机制回收。
标签:obd pattern hide exce let second text 被垃圾回收 启动
原文地址:https://www.cnblogs.com/wwjj4811/p/12623761.html