Man*_*y D 3 c# azure-webjobs azure-webjobssdk webjob
我正在建立一个工作,以定期间隔(比如1分钟)触发.我已成功使用触发式Web作业,并在函数中使用时间跨度硬编码.
public void foo([TimerTrigger("00:01:00")] TimerInfo timer)
Run Code Online (Sandbox Code Playgroud)
现在,如果我想将触发时间从1分钟更改为2分钟,我将重新部署代码.相反,有没有办法从配置文件中使TimeTrigger可配置.
请注意,无法使用动态读取值替换字符串,因为TimerTrigger属性是常量字符串表达式或类型.
经过深入挖掘后,我意识到这可以通过SDK扩展类完成TimerSchedule.
对于它,您需要一个可以用于多个触发器的基类.
class CustomTimerTriggerBase: TimerSchedule
{
TimeSpan timer;
public CustomTimerTriggerBase(string triggerConfigKey)
{
timer=TimeSpan.Parse(ConfigurationManager.AppSettings[triggerConfigKey]);
}
public override DateTime GetNextOccurrence(DateTime now)
{
return now.Add(timer);
}
}
Run Code Online (Sandbox Code Playgroud)
使用此Base生成您的计时器......
public sealed class FooTimer : CustomTimerTriggerBase
{
public FooTimer() : base("FooTimerKey") {}
}
Run Code Online (Sandbox Code Playgroud)
在你的App.config中有一个"FooTimer"键
<add key="FooTimerKey" value="00:02:00" />
Run Code Online (Sandbox Code Playgroud)
在webjob函数中使用此FooTimer类.
public void foo([TimerTrigger(typeof(FooTimer)] TimerInfo timer)
Run Code Online (Sandbox Code Playgroud)
现在,您只需更改app config中的值,而不是重新部署代码. 注意:由于您使用Timespan进行解析,因此字符串可以是TimeSpan格式中定义的任何格式.
事实证明,如今这很容易。只需将应用程序设置作为您的cron计划表达式,它就会为您查找。
例如
public static async Task RunAsync([TimerTrigger("%MYCRON%")]TimerInfo myTimer
Run Code Online (Sandbox Code Playgroud)
查找名为MYCRON的设置,并从那里使用cron表达式
您可以这样做:
public static void Run([TimerTrigger("%MYSCHEDULE%")] TimerInfo myTimer, ILogger log)
Run Code Online (Sandbox Code Playgroud)
MYSCHEDULE环境变量在哪里,您可以将其存储在local.settings.json文件中以及门户中的应用程序设置中。
一个示例值MYSCHEDULE将是:
"MYSCHEDULE": "0 */2 * * * *"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2830 次 |
| 最近记录: |