How Create a Scheduler (e.g. to schedule tweets, or an api request)

后端 未结 4 816
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 00:45

I have a table of schedule items, they may be scheduled for the same time. I\'m wondering how to have them all execute at the correct time when:

The problem I see is

4条回答
  •  礼貌的吻别
    2021-01-14 01:25

    You can put the tasks in threads when you get want them to run:

    public abstract class MyTask {
        public abstract void DoWork();
    }
    
    
    // ...
    
    public void SomeTaskStarter()
    {
        MyTask task = SomeFactoryMethodToCreateATaskInstance();
    
        new Thread(new ThreadStart(task.DoWork)).Start();
    }
    

    MyTask is an abstract class that represents a task to do and it defines a method, DoWork() that will do what you want. SomeFactoryMethodToCreateATaskInstance() will construct a concrete instance of a task and all you need to do is write DoWork() to do what you need to do:

    public class Twitterer : MyTask
    {
        private string _tweet;
        public Twitterer(string tweet)
        {
            _tweet = tweet;
        }
        public override DoWork()
        {
            TwitterApi api = new TwitterApi(); // whatever
            api.PostTweet(tweet);
        }
    }
    

    You will most assuredly want some kind of action of task completion. Whatever you do, the task completion routine should be threadsafe, and should probably be called via BeginInvoke()/EndInvoke() if you need to do any UI-ish work.

    SomeTaskStarter() is best called from a windows service, and will most likely contain an argument with information about what task should be started, etc.

提交回复
热议问题