LoginSignup
0
0

More than 1 year has passed since last update.

スケジュールされているJobの詳細を取得する

Posted at

How to report on Scheduled reports in Salesforce org with list of users it sent out ?

画面から確認できる項目は少ないんですよね。
image.png

何かいい方法はないかと探すとApex Classが紹介されていました。
これを匿名ウィンドウで実行すると結果がメールとして送られてきます。

しかし、メールの添付ファイルはUTF-8なので日本語が含まれているとExcelでは文字化けします。UTF-8を表示できるエディターを使うと文字化けしないです。

さて、少々項目を増やして拡張しました。

public with sharing  class SK_ScheduleJobUtility {

    // ***********************************************************************************
    // Salesforceからスケジュールされたレポートとジョブのリストを取得する             
    // K.Otsubo 2022/07/01   
    // 
    // https://www.sfdcstuff.com/2018/08/way-to-get-list-of-scheduled-reports.html    
    //  run below script to get job list in email
    //  SK_ScheduleJobUtility.findScheduledJobDetails('Report Run');
    //  SK_ScheduleJobUtility.findScheduledJobDetails('Batch Job');
    //  SK_ScheduleJobUtility.findScheduledJobDetails('Scheduled Apex');                                                                                                                
    // ************************************************************************************

    public static void findScheduledJobDetails(string jobType){
        string jobTypeNumber=jobTypeMap.get(jobType);
        if(jobTypeNumber!=null && jobTypeNumber!=''){
            List<CronTrigger> cjList=new List<CronTrigger>();
            Set<string> userIdSet = new Set<string>();
            for(CronTrigger cj :[select id, CronJobDetailId,CronJobDetail.Name,CronJobDetail.JobType, ownerId,State,TimesTriggered,PreviousFireTime,TimeZoneSidKey from CronTrigger where CronJobDetail.JobType=:jobTypeNumber]){
                cjList.add(cj);
                userIdSet.add(cj.ownerId);
            }
            //fetch user information as we cannot access user details using child to parent query using dot notation
            Map<string,User> userMap= new Map<string,User>();
            for(User userRecord:[select id,username,email,IsActive from User where Id IN:userIdSet]){
                userMap.put(userRecord.Id,userRecord);
            }
            string header = 'CronJobDetailId , CronJobDetail Name, CronJobDetail JobType,Submittedby Username,SubmittedBy Userid, User IsActive, User Email ,State,TimesTriggered,PreviousFireTime,TimeZoneSidKey \n';
            string finalstr = header ;
            for(CronTrigger jb: cjList){
                string recordString='';
                DateTime xxx = jb.PreviousFireTime ;
                if(userMap.get(jb.ownerId)!=null){
                   recordString = jb.CronJobDetailId+','+jb.CronJobDetail.Name+','+jobType + ','+userMap.get(jb.ownerId).username + ','+jb.ownerId + ','+userMap.get(jb.ownerId).IsActive + ',' +userMap.get(jb.ownerId).email + ',' + jb.State + ',' + jb.TimesTriggered + ',' + xxx.addHours(9) + ',' + jb.TimeZoneSidKey +'\n';
                }else{
                    recordString = jb.CronJobDetailId+','+jb.CronJobDetail.Name+','+jobType + ', ,'+jb.ownerId + ', , ,' +jb.State + ',' + jb.TimesTriggered + ',' + xxx.addHours(9) + ',' + jb.TimeZoneSidKey +'\n';
                }
                
                finalstr = finalstr +recordString;
            }
            Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
            blob csvBlob = Blob.valueOf(finalstr);
            string csvname= jobType+ ':Schedule Job List'+system.now()+'.csv';
            csvAttc.setFileName(csvname);
            csvAttc.setBody(csvBlob);
            Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
            String[] toAddresses = new list<string> {UserInfo.getUserEmail()};
            String subject =jobType+': Scheduled jobs report';
            email.setSubject(subject);
            email.setToAddresses( toAddresses );
            email.setPlainTextBody(subject);
            email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
            if (test.isRunningTest()) {                
            } else {
                Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            }
            
        }
        
    }
    
    public static Map<string,string>  jobTypeMap = new Map<string, string>{
        'Data Export' => '0',
        'Weekly Export' => '1',
        'Test' => '2',
        'Dashboard Refresh' => '3',
        'Reporting Snapshot' => '4',
        'System' => '5',
        'Scheduled Apex'=>'7',
        'Report Run' => '8',
        'Batch Job' => '9'  ,
        'Reporting Notification' => 'A'    
    };
              

}

ついでに、テストクラスです。

@isTest
public class SK_ScheduleJobUtility_test {
    // ***********************************************************************************
    // Salesforceからスケジュールされたレポートとジョブのリストを取得する  Test Class           
    // K.Otsubo 2022/07/01   
    // 
    // https://www.sfdcstuff.com/2018/08/way-to-get-list-of-scheduled-reports.html    
    //  run below script to get job list in email
    //  SK_ScheduleJobUtility.findScheduledJobDetails('Report Run');
    //  SK_ScheduleJobUtility.findScheduledJobDetails('Batch Job');
    //  SK_ScheduleJobUtility.findScheduledJobDetails('Scheduled Apex');                                                                                                                
    // ************************************************************************************

    
    static testMethod void  SK_ScheduleJobUtility_mainTest() {
        
        Test.startTest();
        	SK_ScheduleJobUtility.findScheduledJobDetails('Report Run');
        Test.stopTest();
        
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0