我想运行java代码一段时间,比如16小时!我有一个运行大约一个小时的java代码。我希望它重复运行16个小时。所以我有一个由用户通过 Jenkins 传递的参数!我使用
访问该值System.getenv("Duration");
现在,我想在指定时间后退出执行。因此,假设用户选择 16,则脚本应运行 16 小时,然后退出。
Accepting input from Jenkins user as shown in the image
我看到了一些其他问题,但大多数都与计时器有关,要么是几秒钟,要么是几分钟。我需要一个有效的解决方案。谢谢:)
仅供引用 - 环境 - Jenkins+TestNG+Maven+Java
编辑:
long start = System.currentTimeMillis();
long end = start + durationInHours*60*60*1000;
while (System.currentTimeMillis() < end)
{
//My code here runs for approx. 50 mins!
}
现在假设用户选择值 3 小时,我希望 while 循环在 3 小时后退出。但这不会发生,因为在检查 while 条件时还没有完成 3 小时。因此,即使是第四次,它也会进入 while 条件(因为耗时是 150 分钟,不到 180 分钟),它会在 3 小时 10 分钟后结束。
如何让它在达到 180 分钟后立即退出 while 循环?
P.S - 我可以先做数学计算,(迭代=durationFromUser/codeDuration),然后运行for循环,但我不想这样做,因为我的脚本长度可能会有所不同。
编辑2:
boolean alive = true;
Timer timer = new Timer();
@Test() //Annotation from TestNG
public void public void jenkinsEntryPoint()
{
String duration = System.getenv("Duration");
int durationInHours=Integer.parseInt(duration);
long end = System.currentTimeMillis() + durationInHours*60*60*1000;
TimerTask task = new TimerTask() {
public void run() {
alive = false;
};
timer.schedule(task, end);
while (alive) {
//My code here runs for approx. 50 mins!
function1();
}
}
void function1() {
function2();
}
private void function2() {
for(i=0;i<8;i++)
{
while(alive)
{
//long running code
sleep(1000);
//Some more code
sleep(2000);
//Some more code
//Suppose time elapses here, I want it to quit
//But its continuing to execute
.
.
.
.
}
}
}
最佳答案
while 条件只会在脚本调用之间进行评估(如您所见)。你必须从它的内部突破你的长跑。
我通常会使用计时器来设置一个“全局” boolean 值,您可以在长时间运行的代码的循环内部检查该 boolean 值。
类似这样的事情。请注意,对“alive”的检查必须在所有长循环中......
boolean alive = true;
Timer timer = new Timer();
public void jenkinsEntryPoint()
long end = System.currentTimeMillis() + durationInHours*60*60*1000;
TimerTask task = new TimerTask() {
public void run() {
alive = false;
};
timer.schedule(task, end);
while (alive) {
//My code here runs for approx. 50 mins!
yourLongRunningCode()
}
public void yourLongRunningCode() {
while (alive) {
doStuff();
}
}
关于java - 在 Jenkins 中在给定的时间内重复运行 java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25419494/