01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.test.unit;
07:
08: import java.sql.Timestamp;
09:
10: /**
11: * This is a self-destructor class to kill a long running process automatically
12: * after a pre-defined time. The class reads the number of minutes from the
13: * system property 'h2.selfDestruct' and starts a countdown thread to kill the
14: * virtual machine if it still runs then.
15: */
16: public class SelfDestructor extends Thread {
17: private static final String PROPERTY_NAME = "h2.selfDestruct";
18:
19: /**
20: * Start the countdown. If the self-destruct system property is set, this
21: * value is used, otherwise the given default value is used.
22: *
23: * @param defaultMinutes the default number of minutes after which the
24: * current process is killed.
25: */
26: public static void startCountdown(int defaultMinutes) {
27: final int minutes = Integer.parseInt(System.getProperty(
28: PROPERTY_NAME, "" + defaultMinutes));
29: if (minutes != 0) {
30: Thread thread = new Thread() {
31: public void run() {
32: for (int i = minutes; i >= 0; i--) {
33: setName("SelfDestructor " + i + " min");
34: try {
35: Thread.sleep(60 * 1000);
36: } catch (InterruptedException e) {
37: // ignore
38: }
39: }
40: String time = new Timestamp(System
41: .currentTimeMillis()).toString();
42: System.out.println(time
43: + " Killing the process after " + minutes
44: + " minutes");
45: Runtime.getRuntime().halt(1);
46: }
47: };
48: thread.setDaemon(true);
49: thread.start();
50: }
51: }
52:
53: /**
54: * Get the string to be added when starting the Java process.
55: *
56: * @param minutes the countdown time in minutes
57: * @return the setting
58: */
59: public static String getPropertyString(int minutes) {
60: return "-D" + PROPERTY_NAME + "=" + minutes;
61: }
62:
63: }
|