一个异步执行任务类

import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class TaskEngine {

	private static TaskEngine instance = new TaskEngine();

	private Timer timer;
	private ExecutorService executor;
	private Map<TimerTask, TimerTaskWrapper> wrappedTasks = new ConcurrentHashMap<TimerTask, TimerTaskWrapper>();

	public static TaskEngine getInstance() {
		return instance;
	}

	private TaskEngine() {
		timer = new Timer("timer", true);
		executor = Executors.newCachedThreadPool(new ThreadFactory() {
			final AtomicInteger threadNumber = new AtomicInteger(1);		
			public Thread newThread(Runnable runnable) {
				//Use our own naming scheme for the threads.
				Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable,"pool-openfire" + threadNumber.getAndIncrement(), 0);
				//Make workers daemon threads.
				thread.setDaemon(true);
				if (thread.getPriority() != Thread.NORM_PRIORITY) {
					thread.setPriority(Thread.NORM_PRIORITY);
				}
				return thread;
			}
		});
	}

	public Future<?> submit(Runnable task) {
		return executor.submit(task);
	}

	public void schedule(TimerTask task, Date time) {
		timer.schedule(new TimerTaskWrapper(task), time);
	}

	public void schedule(TimerTask task, long delay) {
		timer.schedule(new TimerTaskWrapper(task), delay);
	}
	
	public void schedule(TimerTask task, Date firstTime, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        wrappedTasks.put(task, taskWrapper);
        timer.schedule(taskWrapper, firstTime, period);
    }
	
	public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
        TimerTaskWrapper taskWrapper = new TimerTaskWrapper(task);
        wrappedTasks.put(task, taskWrapper);
        timer.scheduleAtFixedRate(taskWrapper, firstTime, period);
    }
	
	public void cancelScheduledTask(TimerTask task) {
        TaskEngine.TimerTaskWrapper taskWrapper = wrappedTasks.remove(task);
        if (taskWrapper != null) {
            taskWrapper.cancel();
        }
    }

	public void shutdown() {
		if (executor != null) {
			executor.shutdownNow();
			executor = null;
		}
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	private class TimerTaskWrapper extends TimerTask {

		private TimerTask task;

		public TimerTaskWrapper(TimerTask task) {
			this.task = task;
		}

		@Override
		public void run() {
			executor.submit(task);
		}
	}

}

 

在C#中,你可以使用定时器 `System.Timers.Timer` 或者 `System.Threading.Timer` 来实现每分钟执行一个异步任务的功能。以下是使用 `System.Timers.Timer` 实现的一个例子: 首先,你需要在项目中引入必要的命名空间: ```csharp using System; using System.Threading.Tasks; using System.Timers; ``` 然后,你可以创建一个定时器实例,并设置其间隔时间,单位是毫秒(1分钟 = 60,000毫秒): ```csharp class Program { private static Timer timer; static void Main(string[] args) { // 创建一个Timer实例,并设置定时器时间间隔为60000毫秒(即1分钟) timer = new Timer(60000); // 设置定时器以异步方式触发事件 timer.Elapsed += async (sender, e) => { // 这里放置你的异步任务代码 await DoAsyncTask(); }; // 开始执行定时器 timer.AutoReset = true; timer.Enabled = true; // 让主线程持续运行,防止程序退出 Console.ReadLine(); } // 这是一个异步方法示例,你需要根据实际情况编写具体的异步任务代码 private static async Task DoAsyncTask() { // 你的异步代码逻辑 // 例如可以是数据库操作、文件操作等 Console.WriteLine("异步任务执行中..."); // 模拟异步操作 await Task.Delay(1000); // 模拟耗时操作 } } ``` 在这个例子中,`DoAsyncTask` 方法是一个异步方法,它被定时器触发并在每次间隔时执行。`System.Timers.Timer` 的 `Elapsed` 事件在定时器到达指定的间隔时触发,并且通过 `+=` 操作符添加了异步的事件处理器。 请注意,定时器运行在自己的线程上,因此它触发的事件处理程序(在这里是匿名函数)是可以异步执行的。如果你的异步任务需要访问共享资源,请确保使用适当的同步机制(如锁)来避免并发问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值