How to use Timer class to call a method, do something, reset timer, repeat?

前端 未结 5 1009
离开以前
离开以前 2020-11-28 08:33

I\'m a Java beginner and have been futzing around with various solutions to this problem and have gotten myself kind of knotted up. I\'ve tried with Threads and then discove

5条回答
  •  醉酒成梦
    2020-11-28 09:08

    If you don't want to use timer class and can use Quartz then perform it like. My main class would be

    import com.google.common.util.concurrent.AbstractScheduledService;
    import org.quartz.CronScheduleBuilder;
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.impl.StdSchedulerFactory;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    import static org.quartz.TriggerBuilder.newTrigger;
    
    import java.util.concurrent.CountDownLatch;
    
    public class Test {
    
    
        public static void main(String[] args) throws Exception{
    
    
            CountDownLatch latch = new CountDownLatch(1);
    
    
            //do schdeuling thing
            JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity(
                    "CronQuartzJob", "Group").build();
    
            // Create a Trigger that fires every 5 minutes.
            Trigger trigger = newTrigger()
                    .withIdentity("TriggerName", "Group")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?"))
                    .build();
    
            // Setup the Job and Trigger with Scheduler & schedule jobs
            final Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
            scheduler.scheduleJob(job, trigger);
    
            //
            latch.await();
    
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        scheduler.shutdown();
                        latch.countDown();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }));
    
        }
    
    
    
    
    
    
    }
    

    and job class would be

    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    
    public class SimpleJob implements Job {
    
    
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("executing task!");
        }
    
    
    }
    

    I would create a executable jar for this and start this using java -jar .. & and Ctrl+C can stop that process , If you want it in background disownit

提交回复
热议问题