1

I have created one Chatter group. In that chatter group i want to post good morning message everyday. I have written batch apex but it is not working. I am sharing my code.

global class PostMessage Implements Database.batchable<sObject>
{

    global Database.queryLocator start(Database.BatchableContext BC)
    {

        return Database.getqueryLocator([Select id,Name from CollaborationGroup where Name='Techila Group' LIMIT 1]);

    }

    global void execute(Database.BatchableContext BC,List<CollaborationGroup> cnt)
    {

        FeedItem post=new FeedItem();

        for(CollaborationGroup c:cnt)
        {
        post.ParentID=c.id;
        post.createdbyID=UserInfo.getuserId();
        post.Body='Good Morning';
        }

        insert post;
    }

    global void finish (Database.BatchableContext BC)
    {

    }

}
3
  • Keith C: My requirement is in batch apex Commented Jul 1, 2015 at 10:02
  • Is this a requirement you were handed? Sometimes requirements include bad assumptions. If the use of batchable makes sense, you will still need to schedule the execution of the batchable i.e. wrap the Database.execute(new PostMessage()); in a scheulable and schedule it.
    – Keith C
    Commented Jul 1, 2015 at 10:05
  • Okay let me see and thanks for help, the point you made is really helpful Commented Jul 1, 2015 at 10:11

2 Answers 2

1

There is no benefit in using a Batchable here as you only ever have one batch with one record. Wrapping the query and feed item insert in a Schedulable and manually setting it to run at e.g. 6am via the "Schedule Apex" button is the approach I would take:

public class PostMessageSchedulable implements Schedulable {
    public class MyException extends Exception {
    }
    public void execute(SchedulableContext sc) {
        String name = 'Techila Group';
        CollaborationGroup[] cgs = [
                select Id
                from CollaborationGroup
                where Name = :name
                limit 1
                ];
        if (cgs.size() == 1) {
            CollaborationGroup cg = cgs[0];
            insert new FeedItem(
                    ParentId = cg.Id,
                    Body = 'Good Morning'
                    );
        } else {
            throw new MyException('CollaborationGroup ' + name + ' not found');
        }
    }
}
-1

@Shantanu Mahajan

the code written by you is working properly. thing is that you need to write schedulable class for this above batch. And after that just add Schedule for created batch using salesforce org as following way...

global class PostMessageforSchedule implements Schedulable {

    global void execute(SchedulableContext ctx)
    {
        PostMessage batch=new PostMessage();
        database.executeBatch(batch);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .