经过大量挖掘,我意识到这可以通过 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);
}
}
使用这个 Base 来生成你的计时器...
public sealed class FooTimer : CustomTimerTriggerBase
{
public FooTimer() : base("FooTimerKey") {}
}
在您的 App.config 中有一个“FooTimer”的键
<add key="FooTimerKey" value="00:02:00" />
在你的 webjob 函数中使用这个 FooTimer 类。
public void foo([TimerTrigger(typeof(FooTimer)] TimerInfo timer)
现在您可以简单地更改应用配置中的值,而无需重新部署代码。
注意:由于您使用 Timespan 进行解析,因此字符串可以是您需要的任何格式,如 TimeSpan 格式中定义的那样。
更新
正如 l--''''''---------'''''''''''' 和 Andy Dobedoe
现在(截至 2019 年)所指出的,实现这一点要简单得多。
public static async Task RunAsync([TimerTrigger("%MYCRON%")]TimerInfo myTimer
找到名为 MYCRON 的设置并从那里使用 cron 表达式