让 Java 在循环之间休眠,在 Linux 上由命令行指定的休眠时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11676670/
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
Getting Java to sleep between loops, sleep time designated by command line on Linux
提问by exit_1
I have been assigned on designing a java program on a linux machine that:
我被指派在一台 linux 机器上设计一个 java 程序:
- Connects to a database
- reads a record
- retrieve certain information and send to Nagios according to a field known as 'threat_level'
- read next record and repeat step number 3 until all records have been read
- 连接到数据库
- 读取记录
- 根据称为“threat_level”的字段检索某些信息并发送到 Nagios
- 读取下一条记录并重复第 3 步,直到读取完所有记录
Now, I needed to get this to run every few minutes; so what my partner did was create a script that uses a loop to run the program, sleeps a few minutes, and repeat.
现在,我需要让它每隔几分钟运行一次;所以我的搭档所做的是创建一个脚本,使用循环来运行程序,休眠几分钟,然后重复。
Recently, my boss told us that its good but would like the whole procedure to be completely self contained in java; meaning that it loops and sleeps within java. On top of that, he would like to have the sleep duration be determined by command line each time that the program is run.
最近,我的老板告诉我们,它很好,但希望整个过程完全独立于java;这意味着它在 java 中循环并休眠。最重要的是,他希望每次运行程序时都通过命令行确定睡眠持续时间。
I did some research and it seems that using Thread.sleep() is inefficient in certain circumstances and I cannot tell if this is one of them or not. Also, I am still unclear on how to have the sleep time be determined via command line upon running the program. I can provide the code if necessary.
我做了一些研究,似乎在某些情况下使用 Thread.sleep() 效率低下,我不知道这是否是其中之一。另外,我仍然不清楚如何在运行程序时通过命令行确定睡眠时间。如果需要,我可以提供代码。
采纳答案by Tomasz Nurkiewicz
Thread.sleep()
is just fine, especially when you want to sleep for "few minutes":
Thread.sleep()
就好了,尤其是当你想睡“几分钟”的时候:
public class Main {
public static void main(String[] args) throws InterruptedException {
final int sleepSeconds = Integer.parseInt(args[0]);
while(true) {
//do your job...
Thread.sleep(sleepSeconds * 1000);
}
}
}
Thread.sleep()
might be inefficient or not precise enough in millisecond time ranges, but not in your case. But if you want the process to run in the same frequency (as opposed to with fixed delay), consider:
Thread.sleep()
在毫秒时间范围内可能效率低下或不够精确,但在您的情况下则不然。但是,如果您希望进程以相同的频率运行(而不是固定延迟),请考虑:
final long start = System.currentTimeMillis();
//do your job...
final long runningTime = System.currentTimeMillis() - start;
Thread.sleep(sleepSeconds * 1000 - runningTime);
This is important of "do your job" part might take significant amount of time and you want the process with exact frequency.
这对于“做你的工作”部分很重要,可能需要大量时间,并且您希望该过程具有精确的频率。
Also for readability consider TimeUnit
class (uses Thread.sleep()
underneath):
同样为了可读性考虑TimeUnit
类(Thread.sleep()
在下面使用):
TimeUnit.SECONDS.sleep(sleepSeconds);
回答by Jeremy Brooks
Set a system property on the command line when the program is started: -Dmy.sleep.time=60000 Then get that parameter: long mySleepTime = System.getProperty("my.sleep.time");
程序启动时在命令行上设置系统属性:-Dmy.sleep.time=60000 然后获取该参数:long mySleepTime = System.getProperty("my.sleep.time");
Look at the Executor framework. The ScheduledExecutorService has a scheduleWithFixedDelay that will probably do what you want (run your code with a delay in between executions).
查看 Executor 框架。ScheduledExecutorService 有一个 scheduleWithFixedDelay ,它可能会做你想做的事情(在执行之间有延迟地运行你的代码)。
回答by CosmicComputer
When you run something in Java with a command-line arguments, they are stored in the main function's parameter args, as in:
当您使用命令行参数在 Java 中运行某些东西时,它们存储在主函数的参数 args 中,如下所示:
public static void main(String[] args)
If you have only the one argument, and it is a number, you can turn it into an integer by using:
如果您只有一个参数,并且它是一个数字,则可以使用以下方法将其转换为整数:
Integer.parseInt(args[0])
Which will return the integer value represented by the String stored as the zero element of the array args.
这将返回由存储为数组 args 的零元素的 String 表示的整数值。
EDIT: Note that you send command-line arguments when you invoke the Java Virtual Machine with:
编辑:请注意,当您使用以下命令调用 Java 虚拟机时发送命令行参数:
java MyCompiledFile arg0 arg1 arg2
Where MyCompiledFile is the name of the file you want to run, and arg0, arg1, and arg2 (you can have as many arguments as you want) are the Strings that are going into args[0], args[1], and args[2] in the parameter passed to main. If you have multiple files in multiple directories, you'll need to specify a classpath - a directory which contains all the directories which contain your files. (Note that these are binary files, the result of compiling source files, not the source files themselves). In that case, use:
其中 MyCompiledFile 是您要运行的文件的名称,arg0、arg1 和 arg2(您可以拥有任意数量的参数)是进入 args[0]、args[1] 和 args 的字符串[2] 在传递给 main 的参数中。如果您在多个目录中有多个文件,则需要指定一个类路径 - 一个包含所有包含您的文件的目录的目录。(请注意,这些是二进制文件,是编译源文件的结果,而不是源文件本身)。在这种情况下,请使用:
java -cp MyClassPath MyCompiledFile arg0 arg1 arg2
Where MyClassPath is the Linux classpath (such as /home/usr/bin).
其中 MyClassPath 是 Linux 类路径(例如 /home/usr/bin)。
回答by MadProgrammer
Take a look at the java.util.Concurrent
API, in particular, you may be interested in the ScheduledExecutorService
看看java.util.Concurrent
API,特别是你可能对ScheduledExecutorService感兴趣