【问题标题】:run a Java program in specific time在特定时间运行 Java 程序
【发布时间】:2011-09-06 06:28:33
【问题描述】:

我需要帮助才能在特定时间(例如下午 2 点)在服务器上运行我的 Java 程序(以索引新文件)。

有人告诉我 Java 有一些叫做作业的东西,但我不知道如何使用它。我试过这个:

 boolean cond=true;
 while(cond){
     @SuppressWarnings("deprecation")
     int heur = new Date().getHours();
     @SuppressWarnings("deprecation")
     int minute= new Date().getMinutes();
     if(heur==16 && minute==02){
         indexer.close();
         end = new Date().getTime();
         File f;
         cond=false;
     }

但是有了这个程序仍在运行。

如何在指定时间运行我的程序?

【问题讨论】:

  • 请正确格式化您的代码

标签: java time runtime timer-jobs


【解决方案1】:

有一个名为Quartz 的API,您的程序可以在其中安排“作业”,届时它将运行它。

在我举个例子之前,试试this link

编辑: 首先,您必须创建一个实现 org.quartz.Job 的类。当您实现它时,您将必须实现方法execute(JobExecutionContext jobExecution),这是触发“触发器”时将运行的方法。

要设置时间表:

SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = null;
try {
    scheduler = schedulerFactory.getScheduler();
}
catch (SchedulerException e) {
    e.printStackTrace();
}

//Set up detail about the job 
JobDetail jobDetail = new JobDetail("jobDetail", "jobDetailGroup", ImplementedJob.class);
SimpleTrigger simpleTrigger = new SimpleTrigger("Trigger Name","defaultGroup", DATE);

// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, simpleTrigger);
// start the scheduler
scheduler.start();

【讨论】:

  • 能否举个例子如何使用!!我下载了它,但我应该把我的代码放在 start() 和 shutdown() 调用之间。我怎样才能给它时间
  • 当标准库有你需要的东西时,为什么要使用石英?
【解决方案2】:

循环中没有Thread.sleep() 调用,所以它会在100% CPU 时“旋转”(不好),但无论如何这是一个糟糕的设计。一个很大的改进是简单地计算“现在”和您希望它运行之间的毫秒数,然后调用 Thread.sleep(n)。

但是,更好的解决方案是使用 JDK 已经提供的。

看看这段代码,它使用 JDK concurrent 库中的类。 这是一个非常简单的例子:

import java.util.concurrent.*;

public static void main(String[] args)
{
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    Runnable runnable = new Runnable() {
        public void run()
        {
            // do something;
        }
    };

    // Run it in 8 hours - you would have to calculate how long to wait from "now"
    service.schedule(runnable, 8, TimeUnit.HOURS); // You can 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多