File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\model\AsyncPeriodicWork.java.html

1 package hudson.model;
2
3 import hudson.security.ACL;
4 import hudson.util.StreamTaskListener;
5 import jenkins.model.Jenkins;
6 import org.acegisecurity.context.SecurityContext;
7 import org.acegisecurity.context.SecurityContextHolder;
8
9 import java.io.File;
10 import java.io.IOException;
11 import java.util.logging.Level;
12
13 /**
14 * {@link PeriodicWork} that takes a long time to run.
15 *
16 * <p>
17 * Subclasses will implement the {@link #execute(TaskListener)} method and can carry out a long-running task.
18 * This runs in a separate thread so as not to block the timer thread, and this class handles
19 * all those details.
20 *
21 * @author Kohsuke Kawaguchi
22 */
23 public abstract class AsyncPeriodicWork extends PeriodicWork {
24 /**
25 * Name of the work.
26 */
27 public final String name;
28
29 private Thread thread;
30
31 protected AsyncPeriodicWork(String name) {
32 this.name = name;
33 }
34
35 /**
36 * Schedules this periodic work now in a new thread, if one isn't already running.
37 */
38 public final void doRun() {
39 try {
40 if(thread!=null && thread.isAlive()) {
41 logger.log(Level.INFO, name+" thread is still running. Execution aborted.");
42 return;
43 }
44 thread = new Thread(new Runnable() {
45 public void run() {
46 logger.log(Level.INFO, "Started "+name);
47 long startTime = System.currentTimeMillis();
48
49 StreamTaskListener l = createListener();
50 try {
51 ACL.impersonate(ACL.SYSTEM);
52
53 execute(l);
54 } catch (IOException e) {
55 e.printStackTrace(l.fatalError(e.getMessage()));
56 } catch (InterruptedException e) {
57 e.printStackTrace(l.fatalError("aborted"));
58 } finally {
59 l.closeQuietly();
60 }
61
62 logger.log(Level.INFO, "Finished "+name+". "+
63 (System.currentTimeMillis()-startTime)+" ms");
64 }
65 },name+" thread");
66 thread.start();
67 } catch (Throwable t) {
68 logger.log(Level.SEVERE, name+" thread failed with error", t);
69 }
70 }
71
72 protected StreamTaskListener createListener() {
73 try {
74 return new StreamTaskListener(getLogFile());
75 } catch (IOException e) {
76 throw new Error(e);
77 }
78 }
79
80 /**
81 * Determines the log file that records the result of this task.
82 */
83 protected File getLogFile() {
84 return new File(Jenkins.getInstance().getRootDir(),name+".log");
85 }
86
87 /**
88 * Executes the task.
89 *
90 * @param listener
91 * Output sent will be reported to the users. (this work is TBD.)
92 * @throws InterruptedException
93 * The caller will record the exception and moves on.
94 * @throws IOException
95 * The caller will record the exception and moves on.
96 */
97 protected abstract void execute(TaskListener listener) throws IOException, InterruptedException;
98 }
99