2016-08-05 43 views
1

我正在使用Azure WebJob从服务总线队列中成功获取消息。 但我想用这个相同的WebJob每5秒运行一些方法。具有队列和System.Threading.Timer的Azure WebJob

我试过了以下方法,本地运行良好,但是当我发布它时只运行一次。 天蓝色日志上没有错误。

我在做什么错了?

感谢您的帮助。

static void Main() 
    { 
     try 
     { 

    var testTimer = new System.Threading.Timer(e => TestMethod(), null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5)); 

      SetupJobHost(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex); 
     } 
    } 

    private static void TestMethod() 
    { 
     Console.WriteLine("Test"); 
    } 

回答

0

根据你的描述,我已经测试了你的代码并在我身边转载。

经过一些试验后,我发现类System.Threading.Timer有问题,如果我们在初始分配后没有引用Timer实例,那么它将被垃圾收集。

请尝试以下方法,看是否有利于:

方法1:部署在调试模式下你webjob不改变任何代码;

方法2:按照以下方式更改您的代码并将其部署到Azure处于发布模式。

try 
{ 
    var testTimer = new System.Threading.Timer(e => TestMethod(), null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5)); 
    SetupJobHost(); 
    testTimer.Dispose(); 
} 
catch (Exception ex) 
{ 
    Console.WriteLine(ex); 
} 

我建议你为更好地了解这个有趣的问题阅读this article。 此外,你可以通过下面的代码实现你的目的:

System.Timers.Timer sysTimer = new System.Timers.Timer(TimeSpan.FromSeconds(5).TotalMilliseconds); 
sysTimer.Elapsed += (s, e) =>TestMethod(); 
sysTimer.Enabled = true; 
1

我建议采取不同的方法,并使用TimerTrigger。您可以使用一个简单的chron表达式,这会导致您的方法按设定的时间表执行。如果你走这条路线,确保你将WebJob部署为触发作业(不连续!),并且在调用JobHostRunAndBlock方法之前调用JobHostConfigurationUseTimers()方法。这比滚动您自己的计时器服务更容易,更清洁。

相关问题