1 29 30 package com.caucho.resources; 31 32 import com.caucho.config.ConfigException; 33 import com.caucho.config.types.CronType; 34 import com.caucho.jca.AbstractResourceAdapter; 35 import com.caucho.log.Log; 36 import com.caucho.util.Alarm; 37 import com.caucho.util.AlarmListener; 38 import com.caucho.util.L10N; 39 40 import javax.annotation.PostConstruct; 41 import javax.annotation.Resource; 42 import javax.resource.spi.BootstrapContext ; 43 import javax.resource.spi.work.Work ; 44 import javax.resource.spi.work.WorkManager ; 45 import java.util.concurrent.Executor ; 46 import java.util.logging.Level ; 47 import java.util.logging.Logger ; 48 49 53 public class CronResource extends AbstractResourceAdapter 54 implements AlarmListener 55 { 56 private static final L10N L = new L10N(CronResource.class); 57 private static final Logger log = Log.open(CronResource.class); 58 59 @Resource 60 private Executor _threadPool; 61 62 private ClassLoader _loader; 63 64 private CronType _cron; 65 66 private Runnable _work; 67 68 private WorkManager _workManager; 69 private Alarm _alarm; 70 71 private volatile boolean _isActive; 72 73 76 public CronResource() 77 { 78 _loader = Thread.currentThread().getContextClassLoader(); 79 } 80 81 84 public void setCron(CronType cron) 85 { 86 _cron = cron; 87 } 88 89 92 public void setWork(Runnable work) 93 { 94 _work = work; 95 } 96 97 100 @PostConstruct 101 public void init() 102 throws ConfigException 103 { 104 if (_cron == null) 105 throw new ConfigException(L.l("CronResource needs a <cron> interval.")); 106 107 if (_work == null) 108 throw new ConfigException(L.l("CronResource needs a <work> task.")); 109 } 110 111 114 public void start(BootstrapContext ctx) 115 { 116 _workManager = ctx.getWorkManager(); 117 118 long now = Alarm.getCurrentTime(); 119 120 long nextTime = _cron.nextTime(now); 121 122 _isActive = true; 123 124 _alarm = new Alarm("cron-resource", this, nextTime - now); 125 } 126 127 130 public void handleAlarm(Alarm alarm) 131 { 132 if (! _isActive) 133 return; 134 135 Thread thread = Thread.currentThread(); 136 ClassLoader oldLoader = thread.getContextClassLoader(); 137 try { 138 thread.setContextClassLoader(_loader); 139 140 log.fine("cron work scheduled: " + _work); 141 142 if (_work instanceof Work ) 143 _workManager.scheduleWork((Work ) _work); 144 else 145 _threadPool.execute(_work); 146 } catch (Throwable e) { 147 log.log(Level.WARNING, e.toString(), e); 148 } finally { 149 thread.setContextClassLoader(oldLoader); 150 } 151 152 long now = Alarm.getCurrentTime(); 153 long nextTime = _cron.nextTime(now); 154 155 _alarm.queue(nextTime - now); 156 } 157 158 161 public void stop() 162 { 163 _isActive = false; 164 _alarm.dequeue(); 165 } 166 } 167 | Popular Tags |