【问题标题】:How to call web service with interval of five minutes? [duplicate]如何以五分钟的间隔调用 Web 服务? [复制]
【发布时间】:2016-05-29 11:56:06
【问题描述】:

我有这个代码:

class ServiceConsumer
{
    static void Main(string[] args)
    {
         //call from here retriveEvents method evry 5 minutes!
    }


    private static void retriveEvents()
    {

        IContract proxy = ChannelFactory<IContract>.CreateChannel(new BasicHttpBinding(),
                                        new EndpointAddress("http://someAddress/Hydrant.svc"));

        using (proxy as IDisposable)
        {
            var rows = proxy.GetData(new DateTime(2000, 5, 1));
        }
    }
}

retriveEvents() 方法正在创建代理并从主机服务中检索数据。 如何每 5 分钟调用一次异步 retriveEvents() 方法来访问主机服务?

【问题讨论】:

  • 使用计时器(滴答)?
  • 这个答案应该适合你:stackoverflow.com/a/21590665/2290059。不要忘记通过调用 Console.ReadLine(); 从主线程等待。
  • @YacoubMassad,我可以使用 while 循环代替 Console.ReadLine(); ?
  • 这不是一个好主意,因为它会让一个 CPU 内核忙于无所事事。

标签: c# .net wcf


【解决方案1】:
static void Main(string[] args)
{
   System.Timers.Timer aTimer = new System.Timers.Timer();
   aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
   aTimer.Interval=360000;
   aTimer.Enabled=true;

   while(true) { }
}

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
     // Do your stuff
     retriveEvents();
}

【讨论】:

  • 我试过了。它会在主函数中抛出所有行,但它永远不会触发 OnTimedEvent 方法
  • 我会使用System.Timer.Timer 而不是System.Threading.Timer,因为它是开箱即用的线程安全的。
  • @Michael 你添加了一个 while(true) 循环吗?因为否则你的程序会在调用retriveEvents之前停止
  • 是的!我试过这个 aTimer.Interval=360000;
  • while(true)?我在上面的代码里改了
【解决方案2】:
var timer = new System.Threading.Timer((e) =>
{
    MyMethod();
}, null, 0, TimeSpan.FromMinutes(5).TotalMilliseconds);

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    相关资源
    最近更新 更多