1. เพิ่ม applicationContext-task.xml ใน WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!--
เพื่อให้สามารถใช้งาน annotation schedule ได้
และเพื่อให้ spring framework มาจัดการ class หรือ method ที่มี annotation นั้นๆ
-->
<task:annotation-driven/>
</beans>
2. เขียน service scheduleProcessor.java
package com.blogspot.na5cent.cronjob;
/**
*
* @author redcrow
*/
public interface Processor {
public void process();
}
ScheduledProcessor.java
package com.blogspot.na5cent.cronjob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
*
* @author redcrow
*/
@Service
public class ScheduledProcessor implements Processor{
private static final Logger LOG = LoggerFactory.getLogger(ScheduledProcessor.class);
@Scheduled(cron = "0 5 0 * * ?") //ที่เวลาเที่ยงคืน 5 นาที ของทุกๆ วัน ให้ทำงานที่ method นี้
@Override
public void process() {
LOG.debug("processing...");
}
}
แค่นี้เราก็จะมี cronjob แบบง่ายๆ มาใช้งานแล้วครับตัวอย่างที่ผมเคยใช้ก็คือ ระบบจองเอกสารครับ ซึ่งมันจะคอยตรวจสอบทุกๆวัน ว่ามีใครได้จองเอกสารไว้บ้าง จากนั้นระบบก็จะไปเอาหมายเลขเอกสารล่าสุดของวันนั้นๆ มาให้
ไม่มีความคิดเห็น:
แสดงความคิดเห็น