Java listener + quartz realizes the function of executing tasks at dynamic time every day

Recently, I have encountered a requirement in my work: to execute a task at a certain time every day. The time is dynamically fetched from the database. For
example today is to execute a task at 22:45:15. Tomorrow's time is 23:45:11 There will be a dynamic time task every day and so on. I have found a lot of information on the


Internet and read a lot of blogs. At this time, I deeply feel the ugliness of the domestic IT technology industry. Many blogs are written incompletely, which wastes my time for more than a day. I have been reading the information on the Internet and running the demo is not what I want. After thinking about it, I finally solved this requirement. It is to realize the periodic task at a fixed time every day through the listener, and then execute the business logic at the specified time through quartz.

Core code:
package com.task;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import com.db.DBUtil;
import com.quartz.CountJob;
import com.util.CommonUtil;

public class TestTimer {
	static int count = 0;

	public static void showTimer() throws ClassNotFoundException, SQLException,
			ParseException {
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				++count;

				System.out.println("time=" + new Date() + " executed" + count + "times"); // 1 time
				// System.out.println("Do business logic here");

				String times = "";
				try {
					times = DBUtil.getTimes(); //This value is taken from the database. It is very simple to take a table. You can build a table locally for testing. Of course, there will be different values ​​every day. It is generated by another project for testing. I am myself You can also do the same for manually changing database values ​​if you just want to see the effect
					System.out.println("Next task time: " + times);
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				Scheduler scheduler = null;
				try {
					scheduler = StdSchedulerFactory.getDefaultScheduler();
				} catch (SchedulerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
				try {
					scheduler.start();
				} catch (SchedulerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}

				if (count >= 2) {
					System.out.println("Indicates that this is the second or more timed task: "+count);
					try {
						scheduler.shutdown(); //Close the previous scheduling task
					} catch (SchedulerException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}  
					
					// restart the task
					try {
						scheduler = StdSchedulerFactory.getDefaultScheduler();
					} catch (SchedulerException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
					try {
						scheduler.start();
					} catch (SchedulerException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
					
					//Start a new scheduling task
					JobDetail jd = new JobDetail("test"+count, "test_group"+count,
							CountJob.class);
					CronTrigger ct = new CronTrigger("test"+count, "test_group"+count);
					// You can modify the following expression to satisfy
					// Time format: <!-- smhdmw(?) y(?) -->, corresponding to: second>minute>hour>day>month>week>year
					try {
						// SimpleDateFormat sdf = new
						// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						// Date date = sdf.parse(times);
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						Date dateSFM = sdf.parse(times);
						Calendar calendarSFM = Calendar.getInstance();
						calendarSFM.setTime(dateSFM);
						// System.out.println("时:"+calendar.get(Calendar.HOUR_OF_DAY)+"分:"+calendar.get(Calendar.MINUTE)
						// +"秒:"+calendar.get(Calendar.SECOND));
						String cron = CommonUtil.makeDailyTriggerCron(
								calendarSFM.get(Calendar.HOUR_OF_DAY),
								calendarSFM.get(Calendar.MINUTE),
								calendarSFM.get(Calendar.SECOND));
						ct.setCronExpression(cron);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
					try {
						scheduler.scheduleJob(jd, ct);
					} catch (SchedulerException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
				} else {
					JobDetail jd = new JobDetail("test", "test_group",
							CountJob.class);
					CronTrigger ct = new CronTrigger("test", "test_group");
					// You can modify the following expression to satisfy
					// Time format: <!-- smhdmw(?) y(?) -->, corresponding to: second>minute>hour>day>month>week>year
					try {
						// SimpleDateFormat sdf = new
						// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						// Date date = sdf.parse(times);
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						Date dateSFM = sdf.parse(times);
						Calendar calendarSFM = Calendar.getInstance();
						calendarSFM.setTime(dateSFM);
						// System.out.println("时:"+calendar.get(Calendar.HOUR_OF_DAY)+"分:"+calendar.get(Calendar.MINUTE)
						// +"秒:"+calendar.get(Calendar.SECOND));
						String cron = CommonUtil.makeDailyTriggerCron(
								calendarSFM.get(Calendar.HOUR_OF_DAY),
								calendarSFM.get(Calendar.MINUTE),
								calendarSFM.get(Calendar.SECOND));
						ct.setCronExpression(cron);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
					try {
						scheduler.scheduleJob(jd, ct);
					} catch (SchedulerException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
				}

			}
		};

		// long delayTime = 24 * 60 * 60 * 1000; // execute every 24 hours
		long delayTime = 3 * 60 * 1000; // execute every minute

		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);// 每天

		calendar.set(year, month, day, 19, 35, 30); // execute every day at 12 noon
		// calendar.set(year, month, day, calendar.get(Calendar.HOUR_OF_DAY),
		// calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
		Date date = calendar.getTime();
		Timer timer = new Timer ();
		System.out.println(date);

		// int period = 2 * 1000;
		// Execute the task at the date time every day and repeat it every 2 seconds
		// timer.schedule(task, date, period);
		// Execute the task at the date time every day, only once
		timer.schedule(task, date, delayTime);

	}

	}




package com.quartz;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class CountJob implements Job
{

    public void execute(JobExecutionContext arg0) throws JobExecutionException
    {
        System.out.println("I am a specific business task, see me indicating that the task is executed!"+ new Date());
        
    }

}


In order to see the test effect, the listener I set up is executed every 3 minutes, as long as it is changed to every day in production.




This is the

complete project of the demo code of the test effect.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327008487&siteId=291194637