You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6自定义插件开发:修改计划任务间隔值

Can I modify the run_interval field of Shopware 6's schedule_task via a custom plugin?

Absolutely feasible! You can totally build a Shopware 6 plugin that lets admins tweak the run_interval value for scheduled tasks right from the admin panel. Here's a practical, step-by-step breakdown to make this happen:

1. Set up the basic plugin skeleton

First, generate a standard Shopware 6 plugin using the CLI command bin/console plugin:create to get the base structure. Make sure your composer.json and plugin.xml have all the required metadata (name, version, author, etc.) to register the plugin properly.

2. Build the admin UI for interval editing

You’ll need a simple, intuitive interface in the admin where admins can select a task and input a new interval.

2.1 Register a custom admin module

In your plugin’s src/Resources/app/administration/src folder, create a new module to house your editor:

  • Add a module/task-interval-editor subfolder, then create main.js to register the module:
import './page/task-interval-editor';

Shopware.Module.register('task-interval-editor', {
    type: 'plugin',
    name: 'TaskIntervalEditor',
    title: 'Task Interval Editor',
    description: 'Adjust run intervals for scheduled tasks',
    color: '#ff3d58',
    icon: 'default-settings',

    routes: {
        index: {
            component: 'task-interval-editor',
            path: 'index'
        }
    },

    navigation: [{
        label: 'Task Interval Editor',
        color: '#ff3d58',
        path: 'task.interval.editor.index',
        icon: 'default-settings',
        parent: 'sw-settings',
        privilege: 'task_interval_editor'
    }]
});
  • Create a page/task-interval-editor.vue file for the UI component:
<template>
    <sw-page :title="$tc('task-interval-editor.general.title')">
        <sw-card>
            <template #content>
                <sw-select
                    v-model="selectedTaskId"
                    :options="taskOptions"
                    label="Select Scheduled Task"
                    placeholder="Choose a task to modify"
                    required
                />
                <sw-text-field
                    v-model="runInterval"
                    label="Run Interval (in seconds)"
                    type="number"
                    min="60"
                    required
                    style="margin-top: 16px;"
                    helpText="Minimum interval is 60 seconds to avoid performance issues"
                />
                <sw-button
                    variant="primary"
                    @click="saveInterval"
                    style="margin-top: 16px;"
                    :disabled="!selectedTaskId || !runInterval"
                >
                    Save New Interval
                </sw-button>
            </template>
        </sw-card>
    </sw-page>
</template>

<script>
export default {
    name: 'task-interval-editor',

    data() {
        return {
            selectedTaskId: null,
            runInterval: null,
            taskOptions: []
        };
    },

    created() {
        this.loadAvailableTasks();
    },

    methods: {
        async loadAvailableTasks() {
            try {
                const response = await this.$http.get('/api/task-interval-editor/tasks');
                this.taskOptions = response.data.map(task => ({
                    label: `${task.name} (Current: ${task.runInterval}s)`,
                    value: task.id
                }));
            } catch (err) {
                this.$notify.error({ title: 'Error', message: 'Failed to load tasks' });
            }
        },

        async saveInterval() {
            try {
                await this.$http.post('/api/task-interval-editor/save', {
                    taskId: this.selectedTaskId,
                    runInterval: parseInt(this.runInterval, 10)
                });
                this.$notify.success({ title: 'Success', message: 'Task interval updated!' });
                this.loadAvailableTasks(); // Refresh task list to show new interval
            } catch (err) {
                this.$notify.error({ title: 'Error', message: 'Failed to update interval' });
            }
        }
    }
};
</script>

3. Add backend API endpoints

Now, create backend routes and a controller to handle the admin’s requests and update the database.

3.1 Define routes

In src/Resources/config/routes.xml, add your API endpoints:

<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns="http://symfony.com/schema/routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/routing https://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="api.task_interval_editor.tasks" path="/api/task-interval-editor/tasks" methods="GET">
        <default key="_controller">YourPluginNamespace\Controller\TaskIntervalController::loadTasks</default>
    </route>

    <route id="api.task_interval_editor.save" path="/api/task-interval-editor/save" methods="POST">
        <default key="_controller">YourPluginNamespace\Controller\TaskIntervalController::saveInterval</default>
    </route>
</routes>

3.2 Build the controller

Create src/Controller/TaskIntervalController.php to handle data fetching and updates:

<?php

namespace YourPluginNamespace\Controller;

use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class TaskIntervalController extends AbstractController
{
    private EntityRepository $scheduleTaskRepository;

    public function __construct(EntityRepository $scheduleTaskRepository)
    {
        $this->scheduleTaskRepository = $scheduleTaskRepository;
    }

    public function loadTasks(Context $context): JsonResponse
    {
        $criteria = new Criteria();
        $criteria->addSelect('id', 'name', 'runInterval');
        
        $tasks = $this->scheduleTaskRepository->search($criteria, $context)->getEntities();
        
        return new JsonResponse($tasks->jsonSerialize());
    }

    public function saveInterval(Request $request, Context $context): JsonResponse
    {
        $taskId = $request->request->get('taskId');
        $runInterval = (int)$request->request->get('runInterval');

        if (!$taskId || $runInterval < 60) {
            return new JsonResponse(['error' => 'Invalid input: Interval must be at least 60 seconds'], 400);
        }

        try {
            $this->scheduleTaskRepository->update([
                [
                    'id' => $taskId,
                    'runInterval' => $runInterval
                ]
            ], $context);

            return new JsonResponse(['success' => true]);
        } catch (\Exception $e) {
            return new JsonResponse(['error' => $e->getMessage()], 500);
        }
    }
}

4. Add admin permissions

To restrict access to authorized admins only, add a custom permission in your plugin.xml:

<permissions>
    <permission>task_interval_editor</permission>
</permissions>

Admins will need this permission assigned to their role to access the Task Interval Editor.

5. Test the plugin

  1. Install and activate your plugin via the admin panel or CLI: bin/console plugin:install YourPluginName -a
  2. Log into the admin, navigate to Settings > Task Interval Editor
  3. Select a task, input a new interval (in seconds), and save
  4. Verify the change by checking the schedule_task table directly, or by monitoring when the task runs next

Key Notes

  • The run_interval field is stored in seconds, so make sure your UI clearly communicates this to avoid confusion
  • Most core Shopware tasks respect the database run_interval value, but double-check any custom tasks you’ve built to ensure they don’t hardcode intervals
  • Always test changes on a staging environment first to avoid disrupting critical production tasks

内容的提问来源于stack exchange,提问作者Emre Ensar Çapcı

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 16:35:13