我已经轻松编写了一个Java方法,等待更改状态,例如" pending"到"跑步"。它定期(延迟N秒)使用 DescribeInstanceRequest 轮询实例状态。
然而,要弄清楚它是否真的被终止是很棘手的,因为我永远不会被终止"实例状态。这是我目前使用的,但我不确定这是否是一个好方法......
/**
* Checks up to 20 times, with linearly increasing delay, for instance state change from the argFromState to the
* argToState.
*
* Typically you would call this method to wait until instance is "terminated", or when instance is "running".
*
* @param argInstanceID
* @param argFromState
* @param argToState
* @see waitForInstance(String argInstanceID)
*/
public void waitForStateChange(String argInstanceID, String argFromState, String argToState) {
List<InstanceStatus> statuses = null;
DescribeInstanceStatusRequest describeInstanceStatusRequest =
new DescribeInstanceStatusRequest().withInstanceIds(argInstanceID);
DescribeInstanceStatusResult describeInstanceResult = null;
LocalDateTime timeStart = LocalDateTime.now();
InstanceStatus status = null;
int code = 0;
String name = argFromState;
boolean inWantedState = false;
int cnt = 1;
while (!inWantedState && (cnt < 20)) {
describeInstanceResult = amazonEC2Client.describeInstanceStatus(describeInstanceStatusRequest);
int numberOfStatuses = describeInstanceResult.getInstanceStatuses().size();
if (numberOfStatuses > 0) {
// We can do this because we requested details of PARTICULAR instance
status = describeInstanceResult.getInstanceStatuses().get(0);
code = status.getInstanceState().getCode();
name = status.getInstanceState().getName();
inWantedState = name.equals(argToState);
} else {
// When instance is terminated, it does not show in the list. That is how we know it is terminated.
if ("terminated".equals(argToState)) {
inWantedState = true;
LOGGER.info("Instance terminated.");
} else {
LOGGER.info("Instance not in the list. It should be.");
}
}
if (!inWantedState) { // status may have just changed...
System.out.println(cnt + "(" + code + "/" + name + ") .. waiting " + (2 * cnt) + "sec for next try.");
try {
Thread.sleep(2 * cnt * 1000);
} catch (InterruptedException ex) {
Logger.getLogger(EC2Wrapper.class.getName()).log(Level.SEVERE, null, ex);
}
} // if
++cnt;
} // while
LocalDateTime timeEnd = LocalDateTime.now();
Duration duration = Duration.between(timeStart, timeEnd);
int secs = (int) duration.getSeconds();
if (secs >= 60) {
LOGGER.log(Level.INFO, "From `{0}` to `{1}` in {2} min.",
new Object[]{argFromState, argToState, secs / 60});
} else {
LOGGER.log(Level.INFO, "From `{0}` to `{1}` in {2} sec.",
new Object[]{argFromState, argToState, secs});
}
} // waitForStateChange() method
答案 0 :(得分:0)
如果您正在谈论维护状态,那么就像我们在异步任务中所做的那样。设置取消(true)将触发具有新状态的回调。我们可以在doinBackground()中访问相同的回调。
while(getStatus() == AsyncTask.Status.RUNNING){
// Do ur code ..
}
getStatus返回的值是用新值更新的,礼貌取消(true)
在您的代码中可以实现同样的效果,如果在此处发布了一些代码段,将会很有帮助。