Apex Exception: Callout from scheduled Apex not supported

You can hit by this error, if you are a rookie in scheduled apex and trying to call external service.

Imagine, that we need to ping this blog from time to time, for an instance once per hour.So you will write something like that

global class PingBlog implements Schedulable{
    global void execute(SchedulableContext SC) {
    HttpRequest req = new HttpRequest();
    req.setEndpoint(‘http://blog.pavelslepenkov.info’);
    req.setMethod(GET);
    Http http = new Http();
    HTTPResponse res = http.send(req);
    System.debug(LoggingLevel.INFO, res.getBody());
 }

It’s simple. After that you will schedule this class

PingBlog pingBlog = new PingBlog();
    String sch =0 00 * * * ?;
    System.schedule(‘ping blog’, sch, pingBlog);

And as a result you will get the following error when your class run:

    Apex script unhandled exception by user/organization: 005E0000001xBrt/00DE0000000xRRo
    Scheduled job ‘ping blog’ threw unhandled exception.
    caused by: **System.CalloutException: Callout from scheduled Apex not supported**.
    Class.PingBlog.execute: line 7, column 1

The solution is pretty simple, just move a callout into method with @future annotation.

global class PingBlog implements Schedulable{
        global void execute(SchedulableContext SC) {
            Ping.pingBlog();
        }
     }

    public class Ping {
        @future(callout=true)
            public static void pingBlog() {
            HttpRequest req = new HttpRequest();
            req.setEndpoint(‘http://blog.pavelslepenkov.info’);
            req.setMethod(GET);
            Http http = new Http();
            HTTPResponse res = http.send(req);
            System.debug(res.getBody());
        }
    }
[apex][exceptions][force.com]