def METHOD_NAME():
    try:
        range_start = arg_datetime('start')
        range_end   = arg_datetime('end')
    except ValueError:
        return bad_request('Invalid start or end time')
    try:
        task = arg_uuid("task")
    except ValueError:
        return bad_request('Invalid task UUID')
    out_format = arg_string("format") or "json"
    if out_format not in CHART_TERM:
        return bad_request("Invalid format '%s'" % (out_format))
    query = ["""
            SELECT
                lower(times),
                upper(times),
                upper(times) - lower(times) AS run_duration,
                task,
                run,
                state_enum,
                state_display,
                task_json,
                task_cli,
                test_json,
                tool_json,
                errors,
                priority
            FROM schedule
            WHERE times && tstzrange(%s, %s, '[)')
    """]
    args = [range_start, range_end]
    if task is not None:
        query.append("AND task = %s")
        args.append(task)
    if out_format != "json":
        query.append("ORDER BY run_duration DESC")
    cursor = dbcursor_query(" ".join(query), args)
    runs = cursor.rowcount
    if out_format == "json":
        result = []
        base_url = pscheduler.api_url_hostport(server_netloc(), "tasks/")
        for row in cursor:
            task_href = base_url +  row[3]
            run_href = "%s/runs/%s" % (task_href, row[4])
            run = {
                "start-time": pscheduler.datetime_as_iso8601(row[0]),
                "end-time": pscheduler.datetime_as_iso8601(row[1]),
                "href": run_href,
                "result-href": "%s/result" % run_href,
                "state": row[5],
                "state-display": row[6],
                "task": row[7],
                "cli": row[8],
                "test": row[9],
                "tool": row[10],
                "errors": row[11],
                "priority": row[12]
            }
            run["task"]["href"] = task_href
            result.append(run)
        # This is sanitized because it contains data from multiple tasks
        return ok_json(result)
    else:
        try:
            data_path = None
            image_path = None
            (_, data_path) = tempfile.mkstemp()
            (_, image_path) = tempfile.mkstemp()
            # Data
            with open(data_path, "w") as data:
                for row in cursor:
                    sched_class = row[5] if row[5] in [ "nonstart" ] \
                                  else row[9]["scheduling-class"]
                    line = "%d %s %s\n" % (
                        CLASS_LEVELS[sched_class],
                        row[0].isoformat(),
                        row[1].isoformat()
                    )
                    data.write(line)
                    log.error("LINE %s", line)
                data.close()
            if out_format == "data":
                return send_file(data_path, cache_timeout=1)
            # Script
            script = CHART_SCRIPT.format(
                term=CHART_TERM[out_format],
                image_file=image_path,
                columns_count=CHART_COLUMNS_COUNT,
                x2tics=CHART_SCRIPT_X2TICS,
                start='"{}"'.format(range_start.isoformat()) if range_start is not None else "",
                end='"{}"'.format(range_end.isoformat()) if range_end is not None else "",
                host=server_hostname(),
                time=pscheduler.time_now().strftime("%Y-%m-%d %T %Z"),
                runs=runs,
                data_file=data_path
            )
            if out_format == "script":
                return ok(script)
            status, out, err = pscheduler.run_program(["gnuplot"], stdin=script)
            if status != 0:
                log.error("GNUPlot failed: %s" % (err))
                return error("Failed to plot schedule; see system logs.")
            return send_file(image_path, cache_timeout=1)
        except Exception as ex:
            log.exception()        
            return error("Unable to plot schedule; see system logs. %s" % (ex))
        finally:
            for target in [ data_path, image_path ]:
                if target is not None:
                    os.unlink(target)
        raise RuntimeError("Reached code that should not be reached.")