[SalesForce] Apex Scheduler stays queued

We have service contracts in our system which have an end date. Every month the Apex code should check if any Service Contracts are about to expire this month, and create an opportunity for that Service Contract.

I am trying to schedule an apex class but it stays on the status Queued when I check 'Apex Jobs' in setup. I wrote the below Apex code and scheduled it through the UI via setup > Apex Classes > Schedule Apex.

 global class serviceContract_Scheduled implements Schedulable
        {
            global void execute(SchedulableContext sc)
            {
                createOpportunityfromServiceContract();
            }

            public void createOpportunityfromServiceContract()
            {

                list<ServiceContract> listServiceContracts = [SELECT ID,Name, AccountId, EndDate FROM ServiceContract WHERE EndDate = This_month];

                for(ServiceContract serv : listServiceContracts)
                {
                  Opportunity opp = new Opportunity();
                  opp.Name = serv.Name;
                  opp.AccountId = serv.AccountId;
                  opp.Type = 'Annual Maintenance';
                  opp.StageName = 'Closed Won';
                  opp.CloseDate = serv.EndDate;
                }

                update listServiceContracts;
            }


        }

Is it the code which is incorrect or am I scheduling it wrong? Any advise would be appreciated!

Based on Mr.Frodo's answer, it seems that by design it stays on 'Queued' status. However, the opportunities are not being created. When I type the query in the developer console, it does find 2 contracts which match the criteria.

Best Answer

Look at this:

Why do I see Apex jobs in Queued status on the "Apex Jobs" page?

By design, scheduled Apex jobs will always stays in the Queued status until the job has no NextFireTime, then it gets marked Completed, or if the job is aborted, then the AsyncApexJob row gets marked Aborted.

update:

In provided code you are not inserting opportunity.

Related Topic