‘壹’ java定时器 timer.schele(new SvgListener(), 0, 20160*60*1000);
你可以尝试用quartz去实现嘛!
1、编写quartz.properties文件:代码如下:
#============================================================================
# Configure Main Scheler Properties
#============================================================================
org.quartz.scheler.instanceName = QuartzScheler
org.quartz.scheler.instanceId = AUTO
#org.quartz.scheler.rmi.export = false
#org.quartz.scheler.rmi.proxy = false
#============================================================================
# Configure ThreadPool
#============================================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 4
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure Plugins
#============================================================================
#org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName = /scheler/quartz_job.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.scanInterval = 10
org.quartz.plugin.shutdownhook.class = org.quartz.plugins.management.ShutdownHookPlugin
org.quartz.plugin.shutdownhook.cleanShutdown = true
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
2、编写quartz_job.xml
<?xml version='1.0' encoding='utf-8'?>
<quartz>
<job>
<job-detail>
<name>test</name>
<group>DEFAULT</group>
<description>testJobhere</description>
<job-class>scheler.TestJob</job-class>
<job-data-map allows-transient-data="true">
<entry>
<key>name</key>
<value>test</value>
</entry>
</job-data-map>
</job-detail>
<trigger>
<cron>
<name>testCron</name>
<group>DEFAULT</group>
<job-name>test</job-name>
<job-group>DEFALUT</job-group>
<!--x/? x表示间断启动时间 ?表示执行间隔时间 13启动时间-->
<cron-expression>0 1/2 23 * * ?</cron-expression>
<!--每月1号0点执行
<cron-expression>0 1 0 1 1-12 ?</cron-expression>
-->
</cron>
</trigger>
</job>
3、编写java代码进行测试:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class ZeroCount implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException
{
String name = context.getJobDetail().getJobDataMap().getString("name");
System.out.println(name);
}
}
出下以下结果表示配置成功:
test
4、此步骤是最后一步也是最重要的一步,只要加入如下代码的到/WEB-INF/web.xml文件中在指定的时间内就会执行系统调度.
<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<init-param>
<param-name>config-file</param-name>
<param-value>/quartz.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>start-scheler-on-load</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
‘贰’ javaweb,监听器和定时器(Quartz)互相调控的问题
publicclassListener{
publicstaticObjectlock=newObject();
publicvoidrun(){
while(true){
synchronized(Listener.lock){
if(hasData()){
//docheckdata
}
nodifyForLock();
}
threadSleep();
}
}
publicstaticbooleanhasData(){
//returnhasdata
}
publicstaticvoidthreadSleep(){
//sleep5second
}
privatevoidnodifyForLock(){
Listener.lock.notify();
}
}
publicclassQuartz{
publicvoidrun(){
synchronized(Listener.lock){
if(Listener.hasData()){
waitForLock();
}
//doquartz
}
}
privatevoidwaitForLock(){
try{
Listener.lock.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
使用同步锁机制,确保监听器和定时器不会同时运行。
使用Wait Nodify机制,确保有数据时定时器会等待,直到数据处理完成。
‘叁’ 如何监控java quartz定时器中的所有定时任务
众所周知spring 的Quartz定时器的功能非常强大,可以在特定的年月日小时分秒的时间点触发时间,完成事件的调度,就像windows中得计划任务一样。下面看一个典型的Quartz定时器的实现:
1、首先实现一个用于被执行的类,这个类用于被定时器调度,这个类不需要继承任何类或者接口,代码如下:
publicTestQuartz{
public void doSomething(){ //TODO } }
2、spring配置文件,具体配置
<!-- 被执行类 -->
<beanid="testQuarzt"class="test.testQuarzt"/>
<!-- 将testQuarzt注入到job中 -->
<beanid="testQuartzJob"class="org.springframework.scheling.quartz.">
<property name="targetObject" ref="testQuarzt" /> <property name="targetMethod" value="doSomething" /> <property name="concurrent" value="false" /> </bean>
<!-- 将job注入到定时触发器 -->
<beanid="testTrigger"class="org.springframework.scheling.quartz.CronTriggerBean"> <property name="jobDetail" ref="testQuartzJob" /> <property name="cronExpression"> <value>0 0 6 * * ?<value> <property> <bean>
<!-- 将定时触发器注入任务工程 -->
<beanclass="org.springframework.scheling.quartz.SchelerFactoryBean"> <property name="triggers"> <list>
‘肆’ Timer和spring的Quartz两种定时器的区别
第一个例子。timer定时器。(这个比较简单,timer是Java.util包下一个类)
为了更好的了解,我写了两个定时器类,很被集成TimerTask。
public class MyTask extends TimerTask{
int count = 0;
public void run() {
System.out.println("定时器TimerTask启动"+count);
count++;
}
}
++++++++++++++++++++++++++++++++++++++++++++
public class MyTaskB extends TimerTask{
int count = 0;
public void run() {
System.out.println("定时器MyTaskB启动"+count);
count++;
}
}
+++++++++++++++++++++++++++++++++++++++++++
在main方法中测试
Timer timer=new Timer();
/**
* 定时器任务制定,执行
* @param tag: 0.在指定的时间里,执行指定的任务;
* 1.在指定的时间里,按照指定的延迟,重复执行指定任务;
* 2.从指定的延迟后,执行指定任务;
* 3.从指定的延迟后,按照指定的延迟,重复执行指定的任务。
*
* @param mydate:指定的执行时间。只有在tag等于0、1才需要指定。
* @param delay: 延迟执行时间,毫秒数。只有在tag等于1、3才需要指定。
* @param period:间隔执行时间,毫秒数。只有在tag等于4才需要指定。
*/
//定时器,执行任务测试
public static void main(String[] args) {
new TestA().timer.schele(new MyTask(), 1000);
new TestA().timer.schele(new MyTaskB(), 4000);
}
注:timer还可以在web中应用。直接把MyTask()和MyTaskB()里面的方法作修改即可,也可以在任务完成后关掉timer定时。
总结:其实timer实现定时任务是很简单的,但是在想法开发是很少用到timer,而是用spring的Quartz。我也在网上找到了一些资料,现在总结一下。
1. Java定时器没有持久化机制。
2. Java定时器的日程管理不够灵活(只能设置开始时间、重复的间隔,设置特定的日期、时间等)//这点感同身受
3. Java定时器没有使用线程池(每个Java定时器使用一个线程)//想必在用timer是遇到了吧。
4. Java定时器没有切实的管理方案,你不得不自己完成存储、组织、恢复任务的措施
一下例子是我在myeclipse中创建了一个小项目,仅供参考。
第一步建立web项目(省略)
第二步导入必要包:如下
用到了一下包:
(这九个包我就不多说了,想必大家都知道他的用处。)
第三步:配置相关文件。web.xml、quartz.properties、quartz_job.xml这三个文件。这里我就没用spring的applicationContext.xml文件来管理了。其实原理都是一样,都是在web启动时监听并启动定时器。配置spring的quartz定时器有两种方法,一种是你用quartz.properties、quartz_job.xml,另外一种是用spring的applicationContext.xml。其实在开发的时候我还是比较喜欢前面一种,因为简单、方便,而用spring的applicationContext.xml里面本来就有各种配置,各种注入,是文件不够清晰(个人见解。呵呵)
(项目中文件的位置,直接放在src目录下)
第四步:web.xml文件配置(监听和启动定时器)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>
org.quartz.ee.servlet.QuartzInitializerListener
</listener-class>
</listener>
<!-- timer -->
<context-param>
<param-name>config-file</param-name>
<param-value>/quartz.properties</param-value>
</context-param>
<context-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
第五步:配置quartz.properties文件
org.quartz.scheler.instanceName = TestScheler
org.quartz.scheler.instanceId = one
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 2
org.quartz.threadPool.threadPriority = 4
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName = quartz_job.xml
注解:主要主用是启动quartz_job.xml。其余的都是一些配置性能的属性,可以在网上查看。
第六步:配置quartz_job.xml(里面主要配置定时器的一下属性)
<?xml version="1.0" encoding="GBK"?>
<quartz>
<!-- 每1分钟执行一次 -->
<job>
<job-detail>
<name>getDate</name><!-- 表示目标定时器的方法(也就是这个方法要定时的作用)-->
<group>job</group>
<job-class>com.timer.util.TimerTask</job-class><!-- 表示上面的getDate()方法路径(即所在的包)-->
</job-detail>
<trigger>
<cron>
<name>t1</name>
<group>job</group>
<job-name>getDate</job-name>
<job-group>job</job-group>
<cron-expression>0 0/1 * * * ?</cron-expression><!-- 设置定时器的触发时间即间隔时间(参数形式可以在网上查到自己想要的形式)-->
</cron>
</trigger>
</job>
</quartz>
第七步:写用两个类来测试定时器是否好用。
public class TimerTask implements Job {
private static Logger logger = Logger.getLogger(TimerTask.class);
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
TimerOperation.getDate();
} catch (Exception ex) {
logger.info(ex.getMessage());
}
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class TimerOperation {
private static Logger logger = Logger.getLogger(TimerOperation.class);
public static void getDate()
{
String strCurrentDateTime = "";
Date currentDateTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strCurrentDateTime = formatter.format(currentDateTime);
logger.info("定时器启动"+strCurrentDateTime);
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
写这两个类就会看出,定时器不能直接调用自己写了定时方法,要先写一个类实现job的接口,然后在实现接口的execute()方法里面调用自己事先写好的定时任务。
好了一个定时器就写好了。运行项目,等待一分钟控制台就会出现
‘伍’ java 定时器 quartz向class文件中传值 只能是传String类型吗
String类型比较通用,传输更方便。使用其他类型需要转换,而且传输的过程还是传输字符
‘陆’ 有java高手么,用过定时器quartZ的,为什么本地eclipse可以执行,放服务器上就不执行
我估计是本地时间和服务器时间不一致导致的。
当在本地eclipse运行时,服务器在本地,假如定时器是要在五点做点什么,
服务器(也就是你本地了,也就是你电脑时间)到五点的时候,就开始运行,不会有偏差。
当你部署到别的地方时,当本地时间五点了,但是服务器时间(就是部署代码的那台电脑时间)才
四点五十九,所以就没运行。
‘柒’ java业务层和spring quartz定时器的问题。。。
test.java应该是个抽象类或者接口吧,testImpl.java在实现时必须实现抽象方法的。
‘捌’ java quartzTask 定时器启动不了问题,问题如图,在线等,谢谢
我感觉没什么问题,不过这个bean你配了吗
还有就是是不是时间没到我看你配的时间是2点15,那应该是凌晨,,,,,,
‘玖’ java:如何使用 quartz定时执行任务,例如定时执行System.out.pintln("aa");看清楚用quartz
}
importstaticorg.quartz.CronScheleBuilder.cronSchele;
importstaticorg.quartz.JobBuilder.newJob;
importstaticorg.quartz.TriggerBuilder.newTrigger;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importorg.quartz.CronTrigger;
importorg.quartz.JobDetail;
importorg.quartz.Scheler;
importorg.quartz.SchelerFactory;
importorg.quartz.impl.StdSchelerFactory;
publicclassTest{
publicvoidgo()throwsException{
//首先,必需要取得一个Scheler的引用
SchelerFactorysf=newStdSchelerFactory();
Schelersched=sf.getScheler();
//jobs可以在scheled的sched.start()方法前被调用
//job1将每隔30分钟执行一次
JobDetailjob=newJob(myJob.class).withIdentity("job1","group1").build();
CronTriggertrigger=newTrigger().withIdentity("trigger1","group1").withSchele(cronSchele("00/30***?")).build();
Dateft=sched.scheleJob(job,trigger);
SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ssSSS");
System.out.pintln("aa");
//开始执行,start()方法被调用后,计时器就开始工作,计时调度中允许放入N个Job
sched.start();
try{
//主线程等待一分钟
Thread.sleep(60L*1000L);
}catch(Exceptione){}
//关闭定时调度,定时器不再工作
sched.shutdown(true);
}
publicstaticvoidmain(String[]args)throwsException{
Testtest=newTest();
test.go();
}
}
‘拾’ 有java高手么,用过定时器quartZ的,急急急!给20分!可以再追加!
大哥,你要是急的话,就先按照例子,让功能先实现,交了差然后自己再慢慢研究...