自spring3.1开始,其计划任务实现非常简单,首先,通过配置类注解@EnableScheduling来开启对计划任务的支持,然后在执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。@Scheduled注解支持很多属性的配置,例如(cron、fixDelasy、fixRate)等
实例代码:
TaskSchedulerConfig.java
package com.minivison.caixing.learn.scheduled;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* <Description> <br>
*
* @author caixing<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2018年04月17日 <br>
*/
@Configuration
@ComponentScan("com.minivison.caixing.learn.scheduled")
@EnableScheduling
public class TaskSchedulerConfig {
}
TaskService.java
package com.minivison.caixing.learn.scheduled;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* <Description> <br>
*
* @author caixing<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2018年04月17日 <br>
*/
@Service
public class TaskService {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrectTime(){
System.out.println("每个5秒执行一次"+DATE_FORMAT.format(new Date()));
}
@Scheduled(cron = "0 52 16 * * *")
public void fixTimeExecution(){
System.out.println("在指定时间"+DATE_FORMAT.format(new Date())+"执行");
}
}
Main.java
package com.minivison.caixing.learn;
import com.minivison.caixing.learn.scheduled.TaskSchedulerConfig;
import com.minivison.caixing.learn.scheduled.TaskService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.imageio.stream.FileImageInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* <Description> <br>
*
* @author caixing<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2018年04月12日 <br>
*/
public class Main {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
//TaskService service = context.getBean(TaskService.class);
//service.reportCurrectTime();
//context.close();
//String str = Base64Utils.encodeToString(image2byte("E:\\123.jpg"));
//System.out.println(str);
}
public static byte[] image2byte(String path) {
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (FileNotFoundException ex1) {
ex1.printStackTrace();
} catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
}