LaravelÖÐÔõÑù²âÊÔÍýÏëʹÃü
laravelÊÇÒ»¿îÊ¢ÐеÄphp¿ò¼Ü£¬ÆÕ±éÓ¦ÓÃÓÚwebÓ¦ÓóÌÐòµÄ¿ª·¢ÖС£ÔÚlaravelÖУ¬ÍýÏëʹÃü£¨scheduled task£©±»³ÆΪʹÃüµ÷Àí£¨task scheduling£©£¬ËüÄÜÈÃÎÒÃÇʵÏÖ×Ô¶¯»¯µÄʹÃüÖ´ÐУ¬ÀýÈçÔÚÌìÌìij¸öÀο¿Ê±¼äÖ´ÐÐijÏîʹÃü¡£¿ÉÊÇ£¬ÔÚÏÖʵӦÓÃÖУ¬ÎÒÃÇÔõÑù²âÊÔÍýÏëʹÃüÄØ£¿±¾ÎĽ«ÏòÄãÏÈÈÝlaravelÖÐÔõÑù²âÊÔÍýÏëʹÃü¡£
ʲôÊÇÍýÏëʹÃü
ÍýÏëʹÃüÊÇÖ¸ÔÚÌض¨µÄʱ¼ä»ò³ÌÐò״̬ÏÂ×Ô¶¯´¥·¢µÄʹÃü¡£¿ÉÒÔ×ÊÖúÎÒÃÇʵÏÖÐí¶à×Ô¶¯»¯µÄ²Ù×÷£¬ÀýÈçÌìÌì׼ʱ·¢ËÍÓʼþ£¬±¸·ÝÊý¾Ý¿â£¬¸üлº´æµÈ²Ù×÷¡£ÔÚLaravelÖÐÍýÏëʹÃüÐèҪͨ¹ýÆô¶¯Ò»¸öÀú³ÌÀ´Íê³É£¬LaravelÌṩÁËArtisanÏÂÁîÐй¤¾ßÀ´ÖÎÀíÕâЩÀú³Ì¡£
LaravelÖеÄʹÃüµ÷Àí
LaravelÖеÄʹÃüµ÷ÀíÆ÷¿ÉÒÔÈÃÎÒÃÇÀû±ãµØ½ç˵ÍýÏëʹÃü£¬²¢×Ô¶¯Ö´ÐÐʹÃü¡£ÎÒÃÇÖ»ÐèÒª½ç˵ʹÃüµÄÖ´ÐÐʱ¼ä¡¢Ö´ÐÐƵÂÊÒÔ¼°ÒªÖ´ÐеÄÏÂÁî¾Í¿ÉÒÔÁË¡£LaravelÌṩÁ˺ÜÊÇÀû±ãµÄʹÃüµ÷Àí¹¦Ð§£¬Í¨¹ýŲÓÃ->cron()ÒªÁì¿ÉÒÔʵÏÖÿ·ÖÖÓ¡¢Ã¿Ð¡Ê±¡¢ÌìÌìÒÔ¼°Ã¿ÖܵÄʹÃüµ÷Àí£¬Ê¾Àý´úÂëÈçÏ£º
$schedule->command('send:remindemail') ->daily() ->timezone('Asia/Shanghai') ->description('send remind email to user');
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÌåÏÖ£¬ÌìÌìÔÚÉϺ£Ê±¼äµÄ0µãÖ´ÐÐ send:remindemail ÏÂÁ²¢ÔÚʹÃüÐÎòÖÐÌí¼ÓÁË˵Ã÷ÎÄ×Ö¡£
LaravelÖеÄʹÃüµ÷Àí²âÊÔ
LaravelÖÐÌṩÁËÒ»ÖÖ×Ô¶¯»¯µÄʹÃüµ÷Àí²âÊÔÒªÁ죬ÎÒÃÇ¿ÉÒÔʹÓÃMockeryÄ£ÄâʹÃüµÄÖ´ÐУ¬È»ºóͨ¹ýLaravel×Ô´øµÄ²âÊÔ¹¤¾ßPHPUnitÀ´ÊµÏÖ²âÊÔ¡£ÊµÏÖ°ì·¨ÈçÏ£º
°ì·¨1£ºÉèÖòâÊÔÇéÐÎ
ÎÒÃÇÐèÒªÔÚ²âÊÔÇ°ÏÈÉèÖòâÊÔÇéÐΣ¬ÓÉÓÚ²âÊÔÇéÐÎÐèҪģÄâÉú²úÇéÐεÄ׼ʱʹÃü¡£ÔÚ .env ÎļþÖÐÉèÖà APP_ENV Ϊ testing £¬ÌåÏÖÄ¿½ñÊDzâÊÔÇéÐΣº
APP_ENV=testing
µÇ¼ºó¸´ÖÆ
°ì·¨2£º½¨Éè²âÊÔÀà
ÎÒÃÇÐèÒª½¨ÉèÒ»¸ö²âÊÔÀàÀ´²âÊÔʹÃüµ÷ÀíÆ÷µÄÊÂÇé¡£²âÊÔÀà¿ÉÒÔÀ©Õ¹ Illuminate\Foundation\Testing\TestCase À࣬ʾÀý´úÂëÈçÏ£º
namespace Tests; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; }
µÇ¼ºó¸´ÖÆ
°ì·¨3£º½ç˵²âÊÔÒªÁì
ÎÒÃÇ¿ÉÒÔÔÚ²âÊÔÀàÖнç˵²âÊÔÒªÁ죬ÏÈʹÓà Mockery Ä£ÄâÒªÖ´ÐеÄÏÂÁȻºóÖ´ÐÐʹÃüµ÷ÀíÆ÷µÄ½ç˵ʹÃü¡£ÔÚʹÃüÖ´ÐÐÍê±Ïºó£¬¿ÉÒÔʹÓà PHPUnit ÌṩµÄһϵÁжÏÑÔÒªÁìÀ´ÅжÏʹÃüÊÇ·ñ±»×¼È·Ö´ÐС£Ê¾Àý´úÂëÈçÏ£º
namespace Tests\Feature; use App\Console\Commands\SendRemindEmail; use Tests\TestCase; use Mockery; use Illuminate\Support\Facades\Artisan; class TaskSchedulerTest extends TestCase { public function testTaskScheduler() { // Arrange $remindEmailCommandMock = Mockery::mock(SendRemindEmail::class); $remindEmailCommandMock->shouldReceive('handle')->once(); $this->app->instance(SendRemindEmail::class, $remindEmailCommandMock); // Act Artisan::call('schedule:run'); // Assert // add your assertions here } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀý´úÂëÖУ¬ÎÒÃÇÊ×ÏÈÄ£ÄâÁË SendRemindEmail ÏÂÁ²¢ÉèÖøÃÏÂÁîºÃ±È»á±»Ö´ÐÐÒ»´Î¡£È»ºó£¬ÎÒÃÇͨ¹ý Artisan ³ÌÐòŲÓÃÁËʹÃüµ÷ÀíÆ÷£¬²¢ÆÚ´ýʹÃüÖ´ÐÐÍê³É¡£×îºó£¬ÎÒÃÇ¿ÉÒÔʹÓÃPHPUnitÌṩµÄÖÖÖÖ¶ÏÑÔÒªÁìÀ´ÅжÏÏÂÁîÖ´ÐÐÊÇ·ñÀֳɡ£
°ì·¨4£ºÔËÐвâÊÔ
µ±ÎÒÃÇÍê³É½ç˵²âÊÔÓÃÀýºó£¬¾Í¿ÉÒÔʹÓÃPHPUnitµÄÏÂÁîÀ´ÔËÐвâÊÔÁË£º
./vendor/bin/phpunit
µÇ¼ºó¸´ÖÆ
ÔÚ²âÊÔÀú³ÌÖУ¬ÎÒÃÇ¿ÉÒÔ×èµ²µ½Ê¹Ãüµ÷ÀíÆ÷Ö´ÐÐʹÃüµÄÀú³Ì£¬²¢Í¨¹ý¶ÏÑÔÀ´ÅжÏʹÃüÊÇ·ñÕý³£Ö´ÐС£
×ܽá
ÔÚ±¾ÆªÎÄÕÂÖУ¬ÎÒÃǼòÆÓÏÈÈÝÁËLaravelÖеÄʹÃüµ÷ÀíÆ÷ÒÔ¼°ÔõÑù¶ÔʹÃüµ÷ÀíÆ÷¾ÙÐе¥Î»²âÊÔ¡£ÍýÏëʹÃü¿ÉÒÔ×ÊÖúÎÒÃÇʵÏÖÐí¶à×Ô¶¯»¯²Ù×÷£¬²¢ÈÃ×ðÁú¿Ê±Ó¦ÓÃÔ½·¢¸ßЧºÍ±ã½Ý¡£Í¬Ê±£¬ÓÅÒìµÄ²âÊÔÒ²¿ÉÒÔÈÃÎÒÃÇÔ½·¢¶¨ÐĵØʹÓÃÍýÏëʹÃü£¬°ü¹ÜʹÃüÄܹ»Õý³£Ö´ÐС£
ÒÔÉϾÍÊÇLaravelÖÐÔõÑù²âÊÔÍýÏëʹÃüµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡