如何创建 Java cron 作业
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22163662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a Java cron job
提问by user3138111
I'm writing a standalone batch Java application to read data from YouTube. I want to set up an cron job to do certain job every hour.
我正在编写一个独立的批处理 Java 应用程序来从 YouTube 读取数据。我想设置一个 cron 作业来每小时做某项工作。
I search and found ways to do a cron job for basic operations but not for a Java application.
我搜索并找到了为基本操作而不是 Java 应用程序执行 cron 作业的方法。
回答by Chi Nguyen
If you are using unix, you need to write a shellscript to run you java batch first.
如果您使用的是 unix,您需要先编写一个 shellscript 来运行您的 java 批处理。
After that, in unix, you run this command "crontab -e
" to edit crontab script.
In order to configure crontab, please refer to this article http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
之后,在 unix 中,您运行此命令“ crontab -e
”来编辑 crontab 脚本。配置crontab请参考这篇文章http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
Save your crontab setting. Then wait for the time to come, program will run automatically.
保存您的 crontab 设置。然后等待时间到,程序会自动运行。
回答by Shoaib Chikate
First I would recommend you always refer docsbefore you start a new thing.
首先,我建议您在开始新事物之前始终参考文档。
We have SchedulerFactory
which schedules Job based on the Cron Expression given to it.
我们有SchedulerFactory
根据给它的 Cron 表达式调度 Job。
//Create instance of factory
SchedulerFactory schedulerFactory=new StdSchedulerFactory();
//Get schedular
Scheduler scheduler= schedulerFactory.getScheduler();
//Create JobDetail object specifying which Job you want to execute
JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);
//Associate Trigger to the Job
CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");
//Pass JobDetail and trigger dependencies to schedular
scheduler.scheduleJob(jobDetail,trigger);
//Start schedular
scheduler.start();
MyJob.class
我的工作类
public class MyJob implements Job{
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("My Logic");
}
}
回答by Indrajith
You can use TimerTask for Cronjobs.
您可以将 TimerTask 用于 Cronjobs。
Main.java
主程序
public class Main{
public static void main(String[] args){
Timer t = new Timer();
MyTask mTask = new MyTask();
// This task is scheduled to run every 10 seconds
t.scheduleAtFixedRate(mTask, 0, 10000);
}
}
MyTask.java
我的任务
class MyTask extends TimerTask{
public MyTask(){
//Some stuffs
}
@Override
public void run() {
System.out.println("Hi see you after 10 seconds");
}
}
AlternativeYou can also use ScheduledExecutorService.
替代方案您还可以使用ScheduledExecutorService。