1,如果只是想简单的写个定时任务,比如10分钟跑一次,那么ScheduledExecutorService是比较方便的,下面举个简单的例子
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CrawlerRun { private static final Logger logger = LoggerFactory.getLogger(CrawlerRun.class); public static void main(String[] args) { ScheduledExecutorService service = Executors.newScheduledThreadPool(8);//先定义8个线程空间 final ScheduledFuture<?> future = service.scheduleAtFixedRate(new CrawlerTest(), 0,10, TimeUnit.MINUTES);//CrawlerTest()是一个实现Runnable接口的类,会自动运行里面的run()方法 //使用1个线程 Thread t= new Thread(new Runnable() { public void run() { try { future.get(); } catch (Exception e) { logger.error(e.getCause().getMessage(), e.getCause());//日志信息输出 future.cancel(false);//关闭线程 } } }); t.start() ; } }
时间: 2024-10-13 22:01:28