Java程序的定时任务(Cron job)

3

我正在使用一个Java程序,在完成一些文件传输后发送电子邮件。我使用Eclipse编写程序。如何设置cron作业以在特定时间执行此Java程序?另外,我的项目中有各种jar文件,请给出建议。


2
你使用Eclipse和拥有多个JAR文件的事实与此有何关联?如果你知道如何启动你的应用程序,使用java -cp ... your.full.ClassName,那么就像为任何其他进程一样设置一个cron job即可。 - JB Nizet
你是指在一个持续运行的程序中工作,还是使用操作系统的cron job启动程序? - Thomas
2
@JB 如果他不知道如何在 Eclipse 中将 JAR 文件放在类路径上而不点击“运行”按钮来运行程序,那么这就是相关的。 - corsiKa
正如@JBNizet所指出的那样,这里的问题是要知道如何从命令行运行Java程序。 - leonbloy
好的。我同意这个观点。那他为什么不问:如何启动Java程序?无论如何(对于楼主),先阅读一下基础知识:http://download.oracle.com/javase/tutorial/getStarted/index.html和http://download.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html - JB Nizet
4个回答

9
  • 编写一个shell脚本,用必要的参数调用你的Java程序。
  • 确保类路径参数指向所需的jar文件。
  • 确保shell脚本具有必要的Unix权限。
  • 通过设置cron作业来安排脚本的调用。

关于cronjob的更多信息,请查看http://en.wikipedia.org/wiki/Cron

这只是我的个人意见...


7

r0ast3d已经给出了快速明确的答案。我需要做更多的搜索来完成每一步,所以我将详细介绍他的步骤:

  1. Write a shell script to invoke your java program with the necessary arguments. Example:

    !/bin/bash
    echo "Running script."
    cd ~/your/classpath/to/java
    java -classpath .:somejar.jar path/to/your/Program
    

    Separate your necessary classpaths with colons (:) rather than semicolons (;) The path to your program should start with your package (find this at the top of the java program)

  2. Make sure that the classpath argument points to the jars that you need. You can check your import statements in your java program to make sure you are specifying all the necessary classpaths. You have to run this script from your java directory, and can use a single period (.) as your first classpath argument.

  3. Make sure that the shell script has necessary unix permissions.

    Run from a terminal: sudo chmod ### yourScript.sh

    Where ### are numbers representing the correct permissions for your system setup.

  4. Schedule the script to be invoked by setting up a cron job.

    Run from a terminal: crontab -e

    This will open your crontab editor. You can add a job in this way:

    */5 * * * * bash /home/scripts/yourScript.sh

    Replace the path to the script with the correct location of your script. This job is set to run every 5 minutes. See http://www.adminschoice.com/crontab-quick-reference/ for a good reference on crontab.

希望这能帮助到有需要的人!

4

如果需要更复杂的任务,可以使用quartz,或者对于简单的任务,可以使用Timer


2

有一个名为cron4j的库http://www.sauronsoftware.it/projects/cron4j/。我以前用过它来安排Java程序每周运行一次。调度语法与crontab相同。问题是,它需要作为后台进程不断运行才能工作。最终我只使用了普通的cron,但如果你不在类Unix系统上,并且没有cron,它可能会很有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接