0

On a WooCommerce website, I have a REST endpoint created with register_rest_route that returns a JSON response. To perform a routine with a certain frequency and urgency, I have added this instruction:

register_rest_route(SK_SYNC_ENDPOINT.'/v1', '/cron', [
    [
        'methods' => WP_REST_Server::READABLE,
        'callback' => function (WP_REST_Request $request) {
            try {
                sk_sync_cron();
                wp_redirect("<my endpoint address>");
                die();
            } catch (\Throwable $e) {
                return rest_ensure_response(
                    new WP_REST_Response([
                            'message' => $e->getMessage(),
                            'trace' => $e->getTrace()
                        ],
                        500
                    )
                );
            }
        },
        'permission_callback' => '__return_true',
    ]
]);

I invoke this function using wget. It works fine, but there is a delay of about two minutes between when the function finishes its job and when wget follows the location header. Why is this happening?

Perhaps wget is waiting for another header since it's a JSON endpoint?

3
  • why are you calling wp_redirect and calling die inside your REST API callback? This is extremely unusual, is your endpoint address on the same install? This Endpoint can never return a success code based on the code shared. Normally cron jobs are implemented using WP Cron
    – Tom J Nowell
    Oct 2, 2023 at 12:41
  • I had added a die() to make sure that nothing was executed after the redirect, but things didn't change; wget still observes a couple of minutes of timeout both with and without die()."
    – Infocurci
    Oct 2, 2023 at 12:53
  • if the cron job takes several minutes then that's not surprising, no redirect HTTP headers can be sent until sk_sync_cron completes, but even then this is very non-standard, and not how REST API endpoints are meant to work. Can you provide context for why a redirect is necessary after running sk_sync_cron? Redirecting in a REST API endpoint is extremely unusual and doesn't make a lot of sense, especially if <my endpoint address> is on the same install as there are better functions to use that avoid the redirect and improve performance. This is important info that isn't being shared
    – Tom J Nowell
    Oct 2, 2023 at 13:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.