Salesforce系列(十):Salesforce Schedule cron定时执行方法!


前言

今天博主将为大家分享Salesforce系列(十):Salesforce Schedule cron定时执行方法!不喜勿喷,如有异议欢迎讨论!

再看这篇文章前博主郑重推荐大家前往阅读我的VsCode安装汉化等系列文章,点这里跳转:VsCode系列(一):下载安装及汉化 以及 Salesforce系列(一):使用Visual Studio Code进行开发!


cron的含义


特殊字符解释:

  • , :代表超过一个月;
  • “-” :定义一个区间,例如JAN-SEP;
  • ** :代表全部,例如月份是*,则代表每个月都会执行;
  • ? :不指定具体值;
  • / :指定增长值,例如Day_of_Month为1/5,则代表第一个月起开始,并在每个月的第五天执行;
  • L :指定范围的结束值,例如每个月末可能为29或31或其他,这个时候采用;
  • W :指定根据具体值找出最近的一周。同时使用L和W可指定出本月的最后一周;
  • “#”:指定每个月的第几周的周几(这个位置不太好叙述,周几/第几周)。#前数字代表周,#后数字代表月。例如2#2,指定每月第二周运行。

限制

  • 同一时间系统只允许存在100个Schedule;
  • Schedule的定时存在推迟问题,具体运行时间根据平台和系统的资源进行调配;
  • Schedule并不支持Callout,但是由于通常和Batch配合,因此不存在这个问题;

心得

Schedule相对而言比较简单。不建议实现太小的循环时间,因为Schedule的运行时间可能推迟,太小的时间差会导致精度大打折扣。

当然也可以在’主页’,进入如下界面:(可以新建一个定时Apex类)


代码配置

调用方式:

System.schedule(name, instance, firetime);

参数说明:

  • name:String类型。代表在Scheduled Jobs管理页面中的标识;
  • instance:实现Schedulable接口的实例;
  • firetime:String类型。触发的时间。

取消方式:和Batch方式一样

System.abortJob(ctId);

管理方式: 和Batch类似,System.schedule()执行后会返回CronTrigger Id,通过CronTrigger来管理。

时间参数的说明:firetime参数实例:= ‘0 0 0 3 9 ? 2022’。分别代表的是:Seconds,Minutes,Hours,Day_of_Month,Month,Day_of_week,[Optional]year

例:每十五分钟执行一次

System.schedule('审批历史15分刷新', '0 15 * * * ?', new ProjectApprovalScheduler());
System.schedule('审批历史30分刷新', '0 30 * * * ?', new ProjectApprovalScheduler());
System.schedule('审批历史45分刷新', '0 45 * * * ?', new ProjectApprovalScheduler());

例:精准到时分


例:每小时,每天执行

System.schedule('每年1月1日运行', '0 0 * 1 1 ?', new QualityGradeAnnualCalculSchedule());
System.schedule('每小时跑一次', '0 0 * * * ?', new QualityGradeAnnualCalculSchedule());

Schedule写法

global with sharing class SchedulerRunSendMessageBatch implements Schedulable
{
    global void execute(SchedulableContext sc)
	{
	    BatchSendMessage bcrbatch = new BatchSendMessage();
         Database.executeBatch(bcrbatch);
	}
}

可能遇到的错误

System.StringException: Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.

ScheduleExamp2 se=new ScheduleExamp2();
string cron='0 0 16 2 1 2 2017';
ID jobid=system.schedule('batchapex', cron,se );

在执行这个的时候,我得到了上面的错误。

解决方法:

问题即将出现,因为您无法同时通过一个星期的某一天和一个月的某一天的参数。(Issue is coming because you can not pass the both a day-of-week AND a day-of-month parameter.)

So your exp can be below(所以你的经验可以在下面)

string cron='0 0 0 ? 2 7 2017';
ID jobid=system.schedule('batchapex', cron,se );

或视图sourceprint吗?

string cron='0 0 0 16 2 ? 2017';
ID jobid=system.schedule('batchapex', cron,se );

好了赶紧去试试吧别光看哈哈!


到这里:Salesforce系列(十):Salesforce Schedule cron定时执行方法!分享完毕了,快去试试吧!


最后

  • 更多参考精彩博文请看这里:《陈永佳的博客》

  • 喜欢博主的小伙伴可以加个关注、点个赞哦,持续更新嘿嘿!


更多推荐

Salesforce系列(十):Salesforce Schedule cron定时执行方法!